Sending connection request to server with data! RRS feed

  • Question

  • Hi

    i'm using System.Net.Sockets.TcpClient & System.Net.Sockets.TcpListener to communicate client(s) / server. here is my sample code in client side :


    And here is my server side code to accept incoming connection request :

    TcpClient client = this._tcpListener.AcceptTcpClient();

    This code works good, but i want have a custom class which hold more data such as ConnectionID, ChatID, etc.

    I want to get this data when server accept incoming connection request, but as u know the 'AcceptTcpClient' method return only 'TcpClient' object and i can't add some data to this object.

    Can anybody help me how to accomplish this task ?

    Thanks in advance.

    Sunday, September 8, 2019 6:26 PM


  • Hi Hamed,

    I would have a custom class that has properties for that information (ConnectionID, ChatID), etc. ... including a property for a TcpClient.
    The server would have a List<T> of that class, to store all the Chat clients that are connecting to your server. Or, maybe a Dictionary might be better:
    public class ChatClient
        public TcpClient Client { get; set;}
        public string ConnectionID { get; set;}
        public string ChatID { get; set;}
        // etc.etc.
    public class MyServer
        private Dictionary<string, ChatClient> chatClients = new Dictionary<string, ChatClient>();
        private void WhereYouAcceptTheIncomingConnectionRequest()
            TcpClient client = this._tcpListener.AcceptTcpClient();
            // Determine if this client is already in the Dictionary.
            // Maybe use the ConnectionID as the Dictionary key. That's up to you.
            if (not_in_the_Dictionary)
                ChatClient cc = new ChatClient();
                cc.Client = client;
                cc.ConnectionID = ConnectionID; // however you determine that
                cc.ChatID = ChatID; // however you determine that
                this.chatClients.Add(ConnectionID, cc);
    You may also want your server to send a message back to the Client, asking for information the client has, but the server does not.

    ~~Bonnie DeWitt [C# MVP]

    Monday, September 9, 2019 12:21 AM