我正在尝试使用System.Net.Sockets
和TcpClient
类在 C# 中为我的游戏编写网络部分。
- 每个更新服务器都向客户端发送信息。
- 所有信息都内置在 2kb 数据包中,因此在 1 次更新中可以发送 1-2-3-5-10 个数据包。
- 客户正在检查信息,如果信息格式正确 - 然后阅读它。
- 一切正常,直到服务器开始尝试发送太多数据包。
- 当它发生时,客户端通常会收到 20-50 个数据包中的错误数据 1 的数据包。
- 例如,1 次更新的 1-2 个数据包通常可以正常接收,3-10 个更新数据包会给出错误的数据流。
- 如果我在 1 次启动多个客户端,那应该从服务器获得相同的数据流 - 它们获得不同数量的成功和失败数据流。
我做错了什么,我该如何逃避这个错误的数据流?
我只是在 1 毫秒内发送了太多数据,并且需要随着时间的推移发送它吗?
这是发送信息:
TcpClient client;
public void SendData(byte[] b)
{
//Try to send the data. If an exception is thrown, disconnect the client
try
{
lock (client.GetStream())
{
client.GetStream().BeginWrite(b, 0, b.Length, null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
这是接收信息:
byte[] readBuffer;
int byfferSize = 2048;
private void StartListening()
{
client.GetStream().BeginRead(readBuffer, 0, bufferSize, StreamReceived, null);
}
private void StreamReceived(IAsyncResult ar)
{
int bytesRead = 0;
try
{
lock (client.GetStream())
{
bytesRead = client.GetStream().EndRead(ar); // просмотр длины сообщения
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
//An error happened that created bad data
if (bytesRead == 0)
{
Disconnect();
return;
}
//Create the byte array with the number of bytes read
byte[] data = new byte[bytesRead];
//Populate the array
for (int i = 0; i < bytesRead; i++)
data[i] = readBuffer[i];
//Listen for new data
StartListening();
//Call all delegates
if (DataReceived != null)
DataReceived(this, data);
}
它是主要的网络代码。