- Home /
Unity TCP async functions
I'm trying to get unity to connect to a TCP server using asynchronous functions. The gist of the call is:
NetworkStream stream = tcpClient.GetStream ();
byte[] bytes = Encoding.ASCII.GetBytes ("1");
stream.BeginWrite (bytes, 0, bytes.Length, new AsyncCallback(sendCallback), stream);
where tcpClient is, as one would expect, a TcpClient. The sendCallback looks like this:
public void sendCallback(IAsyncResult ar)
{
NetworkStream stream = (NetworkStream)ar.AsyncState;
stream.EndWrite (ar);
}
The server does not receive the data until I close the connection. In other words, it doesn't receive the data unless I add (inside the callback) the line:
tcpClient.Close ();
Obviously this is undesirable. If I use synchronous send calls everything works fine. am I doing something wrong or is this a unity bug? If this is a unity bug, I guess my other option would be to go with synchronous calls on a separate thread. Any gotchas to expect there?
Ok I figured it out - somewhat. It was a c# issue. Basically you need to work with the $$anonymous$$anualResetEvent class - see this page. As of now I am just following the example and it seems to work. However there are several things I am still unclear on when it comes to async functions:
1) Do they create new threads? 2) Can they handle concurrent requests safely? For example if you have called beginRead() and two large pieces of data come in at the same time, will I get a jumble of both? 3) What exactly is happening with $$anonymous$$anualResetEvents? Do they block the thread I am on (if indeed, I am implicitly multithreading here)?
I will ask these questions on stack overflow, as they pertain more to c# than to unity.
Ok I take back that last comment. That didn't fix it. I don't know what is happening.