问题描述
我想codeA基本的游戏,当一个球员做一动,对方收到数据包,反之亦然。是,正在被接收的问题仅每第二分组。我知道这是不是连接,因为它是一贯丢失的数据包相同的模式。
I'm trying to code a basic game, where when one player makes a move, the other receives the packet and vice versa. The problem is, only every second packet is being received. I know it's not the connection because it's consistently the same pattern of missed packets.
我的code是如下:
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());
}
任何想法,为什么这会不会发生在我的情况,或在任何其他情况?谢谢!
Any ideas why this would ever happen in my case or in any other situation? Thanks!
推荐答案
发生了什么事是,我有两个不同的AsyncCallbacks为BeginRecieve,一是从套接字创建原来的窗口(欢迎),以及一个用于此窗口。每当其他计算机发送一个信息,那receieved数据是的AsyncCallback的交替的两者之间。
What was happening was that I had two different AsyncCallbacks for BeginRecieve, one from the original window ("Welcome") in which the socket was created, and one for this window. Each time the other computer sent a message, the AsyncCallback that receieved the data was alternating between the two.
这故事告诉我们:只有一个AsyncCallback的一个插座,除非你的需要的只接收每秒分组
Moral of this story: Only have one AsyncCallback for a socket unless you want to only receive every second packet.
这篇关于TCP套接字接收每秒包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!