基本上我需要的是一个 p2p 连接,现在我有一个异步服务器和客户端,它们通过TcpClient
s 相互通信。问题是服务器很少检测到传入的消息,通常只收到第一条消息。我的服务器代码在这里:
public void RecieveAsync()
{
if (netStream == null) netStream = Server.GetStream();
netStream.BeginRead(ReadBuffer, 0, ReadBuffer.Length, recieveCallBack, netStream);
}
public void recieveCallBack(IAsyncResult ar)
{
//try
//{
int rec = netStream.EndRead(ar);
if (rec == 0)
{
if (Disconnected != null)
{
Disconnected(this);
return;
}
}
else
{
if (DataRecieved != null)
{
string RecievedData = Encoding.ASCII.GetString(ReadBuffer, 0, rec);
DataRecieved(RecievedData);
}
ReadBuffer = new byte[1024];
}
}
并且发送数据的客户端代码在这里(它被包裹在一个while循环中,一遍又一遍地发送数据Thread.Sleep(1)
,以更新玩家位置)
public void Send(byte[] data, int index, int length)
{
//add data as state
//socket.NoDelay = true;
Buffer.BlockCopy(data, 0, writeBuffer, index, length);
if (netStream == null) netStream = TcpClient.GetStream();
netStream.BeginWrite(writeBuffer, 0, writeBuffer.Length, sendCallback, netStream);
}
private void sendCallback(IAsyncResult ar)
{
//try
//{
netStream.EndWrite(ar);
//if (ar.AsyncState != null)
//{
// byte[] buffer = (byte[])ar.AsyncState;
// socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, sendCallback, null);
// return;
//}
if (OnSend != null)
{
OnSend(this);
}
//catch (Exception ex)
//{
// System.Windows.Forms.MessageBox.Show(ex.ToString());
// return;
//}
}
默认缓冲区大小为 1024,RecieveAsync
仅在netStream.DataAvailible
为 true 时调用,在服务器循环中不断检查。
编辑 ::
这是调用服务器的代码
while (true)
{
byte[] playerData = NormalText(PreparePlayerData());
server.Send(playerData, 0, playerData.Length);
if (server.Server.Connected)
{
server.netStream = server.Server.GetStream();
while (server.netStream.DataAvailable)
{
server.RecieveAsync();
server.netStream = server.Server.GetStream();
}
}
Thread.Sleep(1);
}