locked
TCP server with multiple Clients

    Question

  • hello,

    im working on a TCP Server + Client
    my Question is:

    my server application
    it starts a new thread and blocks it until connection is accepted
    the listenforClient method

    But how can I manage the connections
    when  multiple Clients are connected to my server

    and they request diffrent things at the same time
    how can i manage that client 1 gets info its need and same for client 2

    Iits multi threaded so multiple Clients can connect but how can i procces the request
    I dont want to put everything in 1 method what than would

    Thanks in Advance

      private void serverstart()
            {
                this.tcplistener = new TcpListener(IPAddress.Any, 49151);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }
    
            private void ListenForClients()
            {
                this.tcplistener.Start();
    
                while (true)
                {
                    //blocks until a client has connected to the server
                    TcpClient client = this.tcplistener.AcceptTcpClient();
    
    
                    // here was first an message that send hello client
                    //
                    ///////////////////////////////////////////////////
    
                    //create a thread to handle communication
                    //with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
    
                    clientThread.Start(client);
                }
            }
    
            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();
    
                byte[] message = new byte[4096];
                int bytesRead;
    
                while (true)
                {
                    bytesRead = 0;
    
                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        //a socket error has occured
                        break;
                    }
    
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        break;
                    }
    
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
    
                    bufferincmessage = encoder.GetString(message, 0, bytesRead);
    
    
                    if (System.Text.RegularExpressions.Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        bufferincmessageresult = bufferincmessage.Split('^');
                        nickname_Cl = bufferincmessageresult[1];
                        password_Cl = bufferincmessageresult[2];
                        getuserdata_db();
                        login();
    
                        byte[] buffer = encoder.GetBytes(inlogmessage);
    
                        clientStream.Write(buffer, 0, buffer.Length);
                        clientStream.Flush();
                    }
    
    
                }
            }


    Arjan Kuijpers


    • Edited by Arjan Kuijpers Monday, June 18, 2012 2:09 PM bad english
    • Moved by Alexander Sun Tuesday, June 19, 2012 6:32 AM Move to more appropriate forum (From:Visual C# General)
    Monday, June 18, 2012 2:03 PM

Answers

  • I just put together something quickly based on your original code.  I commented out some of the code to get it to compile without errors.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace ConsoleApplication1
    {
        class Program
        {
            static List<Listener> listeners = new List<Listener>();
            
            static void Main(string[] args)
            {
                Listener newlistener;
                newlistener = new Listener();
                newlistener.serverstart();
                listeners.Add(newlistener);
                newlistener = new Listener();
                newlistener.serverstart();
                listeners.Add(newlistener);
            }
        }
        class Listener
        {
            Thread listenThread;
            string bufferincmessage;
            TcpListener tcplistener;
            public void serverstart()
            {
                this.tcplistener = new TcpListener(IPAddress.Any, 49151);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }
            private void ListenForClients()
            {
                //this.tcplistener.Start();
                while (true)
                {
                    //blocks until a client has connected to the server
                    //TcpClient client = this.tcplistener.AcceptTcpClient();
                    // here was first an message that send hello client
                    //
                    ///////////////////////////////////////////////////
                    //create a thread to handle communication
                    //with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    //clientThread.Start(client);
                }
            }
            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();
                byte[] message = new byte[4096];
                int bytesRead;
                while (true)
                {
                    bytesRead = 0;
                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        //a socket error has occured
                        break;
                    }
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        break;
                    }
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    bufferincmessage = encoder.GetString(message, 0, bytesRead);
                    //if (System.Text.RegularExpressions.Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    //{
                    //    bufferincmessageresult = bufferincmessage.Split('^');
                    //    nickname_Cl = bufferincmessageresult[1];
                    //    password_Cl = bufferincmessageresult[2];
                    //    getuserdata_db();
                    //    login();
                    //    byte[] buffer = encoder.GetBytes(inlogmessage);
                    //    clientStream.Write(buffer, 0, buffer.Length);
                    //    clientStream.Flush();
                    //}
                }
            }
        }
    }


    jdweng

    Monday, June 25, 2012 12:20 AM

All replies

  • Hi Arjan,

    Thank you for your post.

    I think the Network Class Library forum is more appropriate for you, so I will move your thread to corresponding forum.

    Sorry for any inconvenience.

    Have a nice day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, June 19, 2012 6:32 AM
  • YOu can declare your Listener like this

    List<TcpListener>;

    You can the make an array of listeners.


    jdweng

    Tuesday, June 19, 2012 9:16 AM
  • can you give an example for your solution ??

    because I tried to use a list, but not working.

    Thanks in advance


    Arjan Kuijpers

    Sunday, June 24, 2012 8:58 PM
  • I just put together something quickly based on your original code.  I commented out some of the code to get it to compile without errors.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace ConsoleApplication1
    {
        class Program
        {
            static List<Listener> listeners = new List<Listener>();
            
            static void Main(string[] args)
            {
                Listener newlistener;
                newlistener = new Listener();
                newlistener.serverstart();
                listeners.Add(newlistener);
                newlistener = new Listener();
                newlistener.serverstart();
                listeners.Add(newlistener);
            }
        }
        class Listener
        {
            Thread listenThread;
            string bufferincmessage;
            TcpListener tcplistener;
            public void serverstart()
            {
                this.tcplistener = new TcpListener(IPAddress.Any, 49151);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }
            private void ListenForClients()
            {
                //this.tcplistener.Start();
                while (true)
                {
                    //blocks until a client has connected to the server
                    //TcpClient client = this.tcplistener.AcceptTcpClient();
                    // here was first an message that send hello client
                    //
                    ///////////////////////////////////////////////////
                    //create a thread to handle communication
                    //with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    //clientThread.Start(client);
                }
            }
            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client;
                NetworkStream clientStream = tcpClient.GetStream();
                byte[] message = new byte[4096];
                int bytesRead;
                while (true)
                {
                    bytesRead = 0;
                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch
                    {
                        //a socket error has occured
                        break;
                    }
                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        break;
                    }
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    bufferincmessage = encoder.GetString(message, 0, bytesRead);
                    //if (System.Text.RegularExpressions.Regex.IsMatch(bufferincmessage, Properties.Settings.Default.REQLogin, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    //{
                    //    bufferincmessageresult = bufferincmessage.Split('^');
                    //    nickname_Cl = bufferincmessageresult[1];
                    //    password_Cl = bufferincmessageresult[2];
                    //    getuserdata_db();
                    //    login();
                    //    byte[] buffer = encoder.GetBytes(inlogmessage);
                    //    clientStream.Write(buffer, 0, buffer.Length);
                    //    clientStream.Flush();
                    //}
                }
            }
        }
    }


    jdweng

    Monday, June 25, 2012 12:20 AM