How to properly use TCPClient with unity?

I’ve been writing my own server backend and I’m wanting to connect my unity client to it, now that I’ve done all of the testing with a regular client. (Not unity, console based). I’m curious as to how to do this without the use of threading.

Would I start a CoRoutine to handle the data being passed to the client? (Because usually the client freezes while waiting for data)

Just trying to figure this out, because I know trying to use the Update() function for anything really messes with the client, and starting a new thread pretty much breaks it. (As the thread doesn’t stop when the application closes)

Any kind of networking can usually be done in two different ways: blocking and non blocking. No matter which approach you use, to handle networking in a non blocking way you almost always have to use threads.

The blocking mode (which is the usual one), as you said, will block the thread it runs on until data is available or the task is completed. To keep the main thread running you have to use a seperate thread.

The non blocking mode usually works with callbacks which are fired when data has arrived or any operation has finished. However those callbacks are internally invoked from a seperate thread.

The best approach is usually to create a thread on your own and work in blocking mode. You have to handle stopping your thread properly. When testing in the editor switching between run and edit mode won’t magically “terminate” the threads you’ve started.

So your thread needs:

  • proper synchronisation between your network thread and the main thread (where you most likely need that data).
  • Some kind of a flag variable which you can set to false in order to stop your thread.

If you’re going to use the TcpClient you usually work with the NetworkStream that it provides. The Read method is actually seems to behave like a non blocking method. So if you call it when no data is available it returns immediately with “0” bytes read. However I would recommend to implement everything network related in the seperate network thread. The read method actually is a blocking call but before it actually calls Receive on the underlying socket it checks if data is available. Also things like Connect are blocking anyways.

Everything beginning with “BeginXXX” and “EndXXX” belong to the asychronous / non blocking way. However they use a ThreadPool internally to invoke the callbacks.

Even it’s “usually” not recommended you might want to call Thread.Abort on your network thread when you want it to stop. Most blocking calls should break out by the ThreadAbortException that is thrown.