gpt4 book ai didi

c# - 网络流接收数据与 '\0' 混合

转载 作者:可可西里 更新时间:2023-11-01 02:34:56 24 4
gpt4 key购买 nike

我的服务器正在发送以下数据:

{
"command": 23
}

我的客户正在接收以下数据:

"{\0\r\0\n\0 \0 \0\"\0c\0o\0m\0m\0a\0n\0d\0\"\0:\0 \02\03\0\r\0\n\0}\0"

如您所见,我正在接收发送的数据,但其中混有 \0是什么原因造成的?可能是编码问题?

服务器发送数据的方法:

public void GetBasicInfo()
{
JObject o = new JObject();

o.Add(COMMAND, (int)Command.GetBasicInfo);

byte[] package = GetBytes(o.ToString());
System.Diagnostics.Debug.WriteLine(o.ToString());
networkStream.Write(package, 0, package.Length);
networkStream.Flush();
}

private static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}

客户端读取数据的方法:

private void CommsHandler(TcpClient tcpClient)
{
NetworkStream networkStream = tcpClient.GetStream();

while (true)
{
try
{
string message = ReadResponse(networkStream);
System.Diagnostics.Debug.WriteLine(message);
ParseMessage(message);
}
catch (Exception)
{
break;
}

}

Logger.Log(LogType.Warning, "Communication with server closed");

tcpClient.Close();
SearchForServer();
}

private static string ReadResponse(NetworkStream networkStream)
{
// Check to see if this NetworkStream is readable.
if (networkStream.CanRead)
{
var myReadBuffer = new byte[256]; // Buffer to store the response bytes.
var completeMessage = new StringBuilder();

// Incoming message may be larger than the buffer size.
do
{
var numberOfBytesRead = networkStream.Read(myReadBuffer, 0, myReadBuffer.Length);
completeMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
} while (networkStream.DataAvailable);

return completeMessage.ToString();
}
return null;
}

最佳答案

As you can see I'm receving the data sent, but with those \0 mixed with it. What is causing this? Maybe something with the encoding?

是的。就是这个方法:

private static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}

它以二进制形式复制 char 数据 - 每个字符两个字节。根本不要使用它 - 只需使用 Encoding.GetBytes,选择合适的编码...我建议使用 Encoding.UTF8。在接收端使用相同的编码。请注意,您不能只使用 Encoding.GetString,因为您可能会收到以字符中途结束的数据(如果您有任何非 ASCII 数据)。

我还建议不要使用 DataAvailable 作为消息是否已完成的指示。如果您在同一个流上发送多条消息,您应该为每条消息添加长度前缀(可能是最简单的方法)或使用一些特定数据来指示流的结尾。

关于c# - 网络流接收数据与 '\0' 混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15669532/

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