gpt4 book ai didi

c# - 异步 TCP 服务器/客户端不可靠数据包?

转载 作者:可可西里 更新时间:2023-11-01 02:54:49 36 4
gpt4 key购买 nike

好吧,对于我的游戏,我已经建立了一个服务器/客户端点对点连接,来回发送位置等。

尽管我的消息实际上并没有那么快发送,而且也不可靠。由于部分字符串丢失,有时发送会停止并且线程不会继续(不确定为什么)。t

无论如何,我的接收代码在这里:

    public void RecieveAsync()
{

if (netStream == null) netStream = Server.GetStream();


if (netStream.DataAvailable == false) return;

netStream.BeginRead(ReadBuffer, 0, ReadBuffer.Length, new AsyncCallback(recieveCallBack), netStream);




}


public void recieveCallBack(IAsyncResult ar)
{
//try
//{

String content = String.Empty;

Console.WriteLine("Stuck trying to get data");

int rec = netStream.EndRead(ar);



if (rec > 0)
{


Console.WriteLine(Encoding.ASCII.GetString(
ReadBuffer, 0, rec));

string packet = Encoding.ASCII.GetString(
ReadBuffer, 0, rec);
bool completedPacket = false;
int appendTo = rec;

if (packet.Contains("<eof>"))
{
appendTo = packet.IndexOf("<eof>");
packet.Replace("<eof>", "");
completedPacket = true;
}

SB.Append(packet, 0, appendTo);

// Check for end-of-file tag. If it is not there, read
// more data.

content = SB.ToString();



if (completedPacket)
{
// All the data has been read from the
// client. Display it on the console.


if (DataRecieved != null)
{
string RecievedData = SB.ToString();

DataRecieved(RecievedData);

netStream.Flush();

Array.Clear(ReadBuffer, 0, ReadBuffer.Length);
ReadBuffer = new byte[1024];
}

SB.Clear();

// Echo the data back to the client.
}
else
{
// Not all data received. Get more.
Array.Clear(ReadBuffer, 0, ReadBuffer.Length);
ReadBuffer = new byte[1024];
netStream.BeginRead(ReadBuffer, 0, ReadBuffer.Length, recieveCallBack, netStream);
}


}

}

我在这里发送代码:

    public void Send(byte[] data, int index, int length)
{
//add data as state

//socket.NoDelay = true;

if (netStream == null) netStream = TcpClient.GetStream();

netStream.BeginWrite(data, 0, 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);
}

netStream.Flush();


//catch (Exception ex)
//{
// System.Windows.Forms.MessageBox.Show(ex.ToString());
// return;
//}
}

数据包在 Encoding.ASCII.Getbytes 下。

服务器和客户端都在 while (true) 线程中使用 Thread.Sleep(1) 进行更新。

最佳答案

因为您正试图一点一点地重建一个字符串(如果您使用更常见的多字节编码,例如 UTF8,这种方法将会失败),您的方法很脆弱。

如我的评论所述,您可能会错过您的 <eof>因为它分为两个读取。

IMO,一个更好的方法是用前面的长度字段(4 字节整数)标记您的消息,这样您就不必在消息末尾小心翼翼地试图弄清楚它是否已经完成。

只需将您所有的读数倒入 MemoryStream 中即可直到达到指定的消息长度,然后解码 MemoryStream 的内容使用您认为合适的任何编码。

关于c# - 异步 TCP 服务器/客户端不可靠数据包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498844/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com