这个问题是这个的演变:Issue returning header byte from Python to Unity
现在关于头字节的问题已经解决了,但是在循环过程中我遇到了一个问题
数据传入良好,但在“n”次循环中断后,因为接收到一个json字符串,该字符串包含一个完整的数据结构(带开/闭括号)加上下一个数据结构(带开括号)、一些数据和“image:”中的一些数据和许多“\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;
}
}
}
}
}
}
我这里没有你的Unity环境,所以我不能测试这个
类似这样的循环(可能在协同程序中运行,或者不阻止Unity的默认处理)应该足以处理我们之前建立的形状的消息流(一个4字节的头表示消息长度,后面是那么多字节的JSON)
ReadPacket应该类似于
相关问题 更多 >
编程相关推荐