Unity 3D TCP Server

Finally, after searching many many pages, asking to stackoverflow.com with no answer, i came out with this wonderful listening server code, and without crash ^^, hope it would be useful for other.

using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

public class test : MonoBehaviour {
private bool mRunning;
public static string msg = "";
Thread mThread;
TcpListener tcp_Listener = null;
    void Awake(){
mRunning = true;
ThreadStart ts = new ThreadStart(Receive);
mThread = new Thread(ts);
mThread.Start();
print("Thread done...");
}
    public void stopListening(){
mRunning = false;
void Receive()    {
tcp_Listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8001);
tcp_Listener.Start();
print("Server Start");
while (mRunning)
{
//check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(100);
}
else {
Socket ss = tcp_Listener.AcceptSocket();
BonePos rec = new BonePos();
byte[] tempbuffer = new byte[10000];
ss.Receive(tempbuffer); // received byte array from client
rec.AssignFromByteArray(tempbuffer); //my own datatype
                }
            }
    void Update()   {

    }
    void OnApplicationQuit(){      // stop listening thread

stopListening();     // wait fpr listening thread to terminate (max. 500ms)
        mThread.Join(500);
     }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s