简体   繁体   English

TCP IP socket.receive,在.Net应用程序中但在Unity中未接收到数据

[英]TCP IP socket.receive, data received in .Net application but not in Unity

I send data via TCP from a .NET application to Unity but all bytes aren't received. 我通过TCP将数据从.NET应用程序发送到Unity,但未收到所有字节。 This is the case with a simple .NET wpf application with the same code. 使用相同代码的简单.NET wpf应用程序就是这种情况。 Why is there a difference in Unity? 为什么Unity有区别? Both is based on .NET 4.7? 两者都基于.NET 4.7?

// Data send from .NET application: 
byte[] ba = memoryStream.ToArray();
var buffer = BitConverter.GetBytes(ba.Length);
stm.Write(buffer, 0, buffer.Length);
stm.Write(ba, 0, ba.Length);

// Data receive works in .NET but in Unity not all bytes are received
Socket s;
byte[] buffersizeinbytes = new byte[32];
TcpListener myList = new TcpListener(ipAd, 8001);
s = myList.AcceptSocket();
(...)
int k = s.Receive(buffersizeinbytes);
int size = BitConverter.ToInt32(lengthb, 0); // size of buffer
byte[] buffer = new byte[size]; 
int receivedByteCount = s.Receive(buffer);

While it may seem confusing that your code works in one application, but not in Unity, that is not the core of your problem. 虽然您的代码可以在一个应用程序中运行,而不能在Unity中运行,这似乎令人困惑,但这不是问题的核心。 You seem to be making the assumption that when you send chunks of data, you will receive them in that manner as well. 您似乎在假设当您发送数据块时,也会以这种方式接收它们。 That's not the case. 事实并非如此。

Calling Receive will result in you getting some data, up to a maximum of the amount you ask for, but you may not get all. 致电Receive将使您获得一些数据,最多达到您要的最大数量,但您可能无法获得全部。 The return value will tell you exactly how much you did actually get. 返回值将告诉您确切的实际收入。 If you expect more, you will have to call Receive again, until you have all the data you expect. 如果期望更多,则必须再次致电Receive ,直到获得所有期望的数据为止。

There are various overloads of Receive which allow you to specify an offset into a buffer. Receive有多种重载,可让您指定缓冲区的偏移量。 So if you're expecting 32 bytes of data, but you get only 16, you can call Receive again, with the same buffer, but specify an offset so your buffer will be filled from its first empty entry onward. 因此,如果您希望获得32个字节的数据,但是只有16个字节,则可以使用相同的缓冲区再次调用Receive,但是要指定一个偏移量,以便从第一个空条目开始填充缓冲区。

So it's not so much Unity that's doing anything strange, but rather you lucking out that all works without issue in your other application. 因此,要做很多奇怪的事情不是Unity,而是您很幸运,所有其他应用程序都可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM