我正在尝试编写一个基本游戏,当一个玩家移动时,另一个玩家会收到数据包,反之亦然。问题是,只有每一个第二个数据包被接收。我知道这不是连接,因为它始终是相同的丢失数据包模式。
我的代码如下:
Socket serverSocket
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//Take socket from another window that created it and start receiving
serverSocket = Welcome.MainSocket;
serverSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
//The initial definition of the socket was this (in the Welcome window)
//MainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//MainSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//MainSocket.Bind(new IPEndPoint(OwnLocal, OwnPort));
//MainSocket.Connect(Address, OppositePort);
}
private void OnReceive(IAsyncResult ar)
{
OnlineData Data = OnlineData.FromByte(Buffer);
//Do stuff with data on UI thread
if (Data is MoveData)
{ App.Current.Dispatcher.Invoke((Action)delegate
{
((MoveData)Data).Sync(Game, Me == Game.PlayerOne ? 1 : 2);
});
}
//End receive and start receiving again
serverSocket.EndReceive(ar);
serverSocket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
//Called each time the player makes a move
void SocketSend(OnlineData Data)
{
serverSocket.Send(Data.ToByte());
}
任何想法为什么会在我的情况或任何其他情况下发生这种情况?谢谢!