Reputation: 35733
I send data via TCP from a .NET application to Unity but all bytes aren't received. This is the case with a simple .NET wpf application with the same code. Why is there a difference in Unity? Both is based on .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);
Upvotes: 1
Views: 280
Reputation: 3383
Unity installer for some reason adds a firewall rule in Windows blocking TCP communication over LAN (this doesn't happen on Linux or macOS). Look at advanced firewall rules in Windows for "Incoming connections" and delete it for Unity editor.
Also I have working TCP,UDP,RUDP socket API thats working in Unity3D editor on Win, Mac and Lin (should work on mobile platforms as well)
Link here: Orbital-Framework
Upvotes: 0
Reputation: 20038
While it may seem confusing that your code works in one application, but not in Unity, that is not the core of your problem. 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. 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.
There are various overloads of Receive
which allow you to specify an offset into a buffer. 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.
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.
Upvotes: 1