【发布时间】:2021-03-24 22:45:12
【问题描述】:
这个问题是这个问题的演变:Issue returning header byte from Python to Unity
现在关于头字节的问题已经解决了,但是我在循环过程中遇到了问题。
数据传入良好,但在“n”次循环中断后,因为接收到一个带有开/关括号的完整数据结构的 json 字符串加上带开括号的下一个数据结构,一些数据和“图像: " 一些数据和许多 "\0" 除非右括号.. 并且 json 解析器显然会中断。为什么以及我能做什么?谢谢 下面代码修改:
IEnumerator Client()
{
while (!IsConnected(client))
{
try
{
client = new TcpClient(host, port);
s = client.GetStream();
byte[] byteBuffer = Encoding.UTF8.GetBytes("Connected to client");
s.Write(byteBuffer, 0, byteBuffer.Length);
while (true)
{
if (s.DataAvailable)
{
while (s.DataAvailable)
{
var header = new byte[4];
s.Read(header, 0, header.Length);
var fileSize = BitConverter.ToUInt32(header,0);
StringBuilder myCompleteMessage = new StringBuilder();
MemoryStream ms = new MemoryStream();
int increment = 0;
while (ms.Length < fileSize)
{
byte[] dataReceived = new byte[fileSize];
increment = s.Read(dataReceived, 0, dataReceived.Length);
ms.Write(dataReceived.Take(increment).ToArray(), 0, increment);
}
myCompleteMessage.AppendFormat("{0}", Encoding.UTF8.GetString(ms.GetBuffer()));
JSONNode data = JSONNode.Parse(myCompleteMessage.ToString());
....
// Do work with myCompleteMessage
yield return null;
}
}
}
}
}
}
【问题讨论】:
-
为什么要写
"Connected to client"到socket? -
仅供测试