Search code examples
c#network-programmingtcptcpclienttcplistener

TCPListener with multiple Clients


I use layered architecture. I create a server. I want the server to listen when the data arrives. This is my server code in the DataAccess layer.

public class ServerDal : IServerDal
{
    private TcpListener server;
    private TcpClient client = new TcpClient();
    public bool ServerStart(NetStatus netStatus)
    {
        bool status = false;
        try
        {
            server = new TcpListener(IPAddress.Parse(netStatus.IPAddress), netStatus.Port);
            server.Start();
            status = true;
        }
        catch (SocketException ex)
        {
            Console.WriteLine("Starting Server Error..." + ex);
            status = false;
        }
        return status;
    }

    public string ReceiveAndSend(NetStatus netStatus)
    {
        Byte[] bytes = new Byte[1024];
        String data = null;

        Mutex mutex = new Mutex(false, "TcpIpReceive");
        mutex.WaitOne();

        if (!client.Connected)
            client = server.AcceptTcpClient();
        try
        {
            NetworkStream stream = client.GetStream();
            int i;
            if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
            {
                data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                Console.WriteLine("Received: " + data);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Connection Error..." + ex);
            client.Close();
        }
        finally
        {
            mutex.ReleaseMutex();
        }
        return data;
    }
}

I can listen to the client that first connects to the server. When the first connecting client disconnects, I can listen to the second connecting client. I want to listen when both clients send data. How can I do that ? Thanks for your help.


Solution

  • I fixed the problem.

        static List<TcpClient> tcpClients = new List<TcpClient>();
        public void ReceiveMessage(NetStatus netStatus)
        {
            try {
                TcpClient tcpClient = server.AcceptTcpClient();
                tcpClients.Add(tcpClient);
    
                Thread thread = new Thread(unused => ClientListener(tcpClient, netStatus));
                thread.Start();
            }
            catch(Exception ex) {
                Console.WriteLine("[ERROR...] Server Receive Error = {0} ", ex.Message);
            }
    
        }
        public void ClientListener(object obj, NetStatus netStatus)
        {
            try 
            {
                TcpClient tcpClient = (TcpClient)obj;
                StreamReader reader = new StreamReader(tcpClient.GetStream());
    
                while(true)
                {
                    string message = null;
                    message = reader.ReadLine();
                    if(message!=null)
                    {
                        netStatus.IncommingMessage = message;
                        Console.WriteLine("[INFO....] Received Data = {0}", message);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("[ERROR....] ClientListener Error = {0}", ex.Message);
            }
        }