Quantcast
Channel: Answers by "knoggly"
Viewing all articles
Browse latest Browse all 6

Answer by knoggly

$
0
0

Hello,

you have to add a flag to your Thread like "isRunning" and use this instead of "while(1)"

while(isRunning){
 ...
}

additionally you need a method to set this flag from outside. For example on OnApplicationQuit

Then you have to synchronize with the Serverthread to wait until it has finished its last loop.

To prevent your tcpListener to block until a connection comes in, you can use TCPListener.pending() to check if a connection is pending and just then call "AcceptTCPClient".

So a little example would be the following:

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

public class MyServerListener : MonoBehaviour
{
    private bool mRunning;

    string msg = "";
    Thread mThread;
    TcpListener tcp_Listener = null;

    void Start()
    {
        mRunning = true;
        ThreadStart ts = new ThreadStart(SayHello);
        mThread = new Thread(ts);
        mThread.Start();
        print("Thread done...");
    }

    public void stopListening()
    {
        mRunning = false;
    }

    void SayHello()
    {
        try
        {
            tcp_Listener = new TcpListener(52432);
            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
                {
                    print("1");
                    TcpClient client = tcp_Listener.AcceptTcpClient();
                    print("2");
                    NetworkStream ns = client.GetStream();
                    print("3");
                    StreamReader reader = new StreamReader(ns);
                    print("4");
                    msg = reader.ReadLine();

                    print(msg);

                    reader.Close();
                    client.Close();
                }
            }
        }
        catch (ThreadAbortException)
        {
            print("exception");
        }
        finally
        {
            mRunning = false;
            tcp_Listener.Stop();
        }
    }

    void OnApplicationQuit()
    {
        // stop listening thread
        stopListening();
        // wait fpr listening thread to terminate (max. 500ms)
        mThread.Join(500);
    }

}

For Details about the functions check the msdn-manual. I did not run the code, so please don't expect it to be bug-free :), but I think you'll get the point.

cheers knoggly


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>