public class MultiplayerState : IState
{
Game1 game;
Socket sck;
EndPoint epLocal, epRemote;
SpriteFont font;
string localIp, remoteIp = "192.168.137.2";
int localPort = 80, remotePort = 80;
public MultiplayerState(Game1 game)
{
this.game = game;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
localIp = GetLocalIP();
remoteIp = localIp;
Console.WriteLine(localIp);
connect();
sendMessage("Hello");
}
private string GetLocalIP()
{
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
return ip.ToString();
}
return "127.0.0.1";
}
void connect()
{
epLocal = new IPEndPoint(IPAddress.Parse(localIp), localPort);
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(remoteIp), remotePort);
sck.Connect(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
Console.WriteLine("Connected to " + remoteIp);
}
void sendMessage(string str)
{
System.Text.ASCIIEncoding enc = new ASCIIEncoding();
byte[] msg = new byte[8000];
msg = enc.GetBytes(str);
sck.Send(msg);
}
void MessageCallBack(IAsyncResult aResult)
{
Console.WriteLine("Message received");
byte[] buffer = new byte[1500];
int size = 0;
size = sck.EndReceiveFrom(aResult, ref epRemote);
if (size > 0)
{
byte[] receivedData = new Byte[1464];
receivedData = (byte[])aResult.AsyncState;
ASCIIEncoding eEncpding = new ASCIIEncoding();
string receivedMessage = eEncpding.GetString(receivedData);
Console.WriteLine("received message:" + receivedMessage);
}
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
}
public void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
sck.Close();
game.gameState = new MenuState(game);
}
if (Keyboard.GetState().IsKeyDown(Keys.Enter))
sendMessage("Hello");
}
}
这是我将一些字符串发送到网络上的计算机的代码。在课外需要时调用Update方法。当我创建一个实例时,一切都运行良好,直到我按Enter键,它应该在控制台上写“Hello”,但没有任何反应。另一个问题是,当我创建类的第二个实例时,代码会卡在Console.WriteLine(localIp)
行上,没有任何反应。为什么会发生这种情况?我该如何解决?