How to keep the server listening?

Hi everyone,

I got this server code from another post and it works very well, but I would like to know, how do I change the code to make it to keep receiving messages indefinitly.

using UnityEngine;

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

public class Servidor1 : MonoBehaviour
{
private bool mRunning;

public static 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(54321);
        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();
    }
}

public static string mssg(){
		return msg;
	
}

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

}

i’d recommend to split your server into threads, accepting clients and reading messages.

  • accepting clients waits for clients to connect and stores them into a pool. important: the tcp connection won’t be closed then.

  • reading messages loops through all clients in the pool that are active and checks whether they have sent any messages like NetworkStream.DataAvailable and eventually reads it. (the client may send multiple game messages inside one networkstream message, you may wanan check that)

additionally: you may need a cleanup procedure to continually check if a connection is disconnected and remove it from the pool