none
C# TCP/IP Multiple Clients RRS feed

  • Question

  • I'm trying to change my TCP/IP media streaming app from accepting only 1 client to multiple.  I have these two functions

        private TcpListener     _tcpListener;
        private List<TcpClient> _clientList;

    public void StartServer( ) { _tcpListener.Start( ); _tcpListener.BeginAcceptTcpClient( new AsyncCallback( ClientConnected ), null ); } /// <summary> /// Call back when a client connects to the server /// </summary> /// <param name="AR"></param> public void ClientConnected( IAsyncResult AR ) { TcpClient client = _tcpListener.EndAcceptTcpClient( AR ); _networkStream = _tcpClient.GetStream( ); _clientList.Add( client ); _tcpListener.BeginAcceptTcpClient( new AsyncCallback( ClientConnected ), null ); }

    Where _tcpListener and _clientList are global to my class.

    I have another function where I'm sending an image to a single client.  But as mentioned, I'm trying to extend this to now service multiple clients.

    Is it safe to say, that in my function where I'm sending my image to the client, if I want to send multiple clients the exact same image, I would have to iterate over every client in the List<TcpClient> list, get it's "NetworkStream" object and call it's send method?  Or is there a simpler approach? One that does not seem like it would have so much overhead?


    Rick



    • Edited by m00n Thursday, February 28, 2019 12:03 AM
    Thursday, February 28, 2019 12:00 AM

Answers

  • Hi m00n,

    Thank you for posting here.

    For your question, you could download the source file from the code project TCPIP Server and Client example for reference.

    It provides example of a TCPIP server that listens and can serve multiple client connections.

    https://www.codeproject.com/Articles/1215517/TCPIP-Server-and-Client-example

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 28, 2019 5:39 AM
    Moderator

All replies

  • Hi m00n,

    Thank you for posting here.

    For your question, you could download the source file from the code project TCPIP Server and Client example for reference.

    It provides example of a TCPIP server that listens and can serve multiple client connections.

    https://www.codeproject.com/Articles/1215517/TCPIP-Server-and-Client-example

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, February 28, 2019 5:39 AM
    Moderator
  • Ok cool. I'll give it a look. Thanks for the link. 
    Sorry for the duplicate post. 

    Rick

    Thursday, February 28, 2019 6:15 AM
  • Hi Wendy... The example you provided gave me the answer I was looking for.  Yep, his/her example is doing just that. Iterating over a list (in this example a dictionary) of client sockets and sending to each individually.

    foreach( int clientId in workerSockets.Keys ) { if( workerSockets[ clientId ].UserSocket.Connected ) { try { workerSockets[ clientId ].UserSocket.Send( message ); } catch { ClientsToRemove.Add( clientId ); } Thread.Sleep( 10 );// this is for a client Ping so stagger the send messages } else ClientsToRemove.Add( clientId );
    }




    Rick





    • Edited by m00n Thursday, February 28, 2019 5:07 PM
    Thursday, February 28, 2019 5:03 PM
  • Hi m00n,

    If your question has been solved, please mark the useful reply as answer to close the thread. This will make answer searching easier in the forum and be beneficial to community members.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 1, 2019 5:10 AM
    Moderator
  • Hi /* Server Program */ using System;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    public class serv { public static void Main()
    {
        try
        {
            IPAddress ipAd = IPAddress.Parse("127.0.0.1");
            // use local m/c IP address, and // use the same in the client /* Initializes the Listener */ TcpListener myList=new TcpListener(ipAd,8888);
            /* Start Listeneting at the specified port */
            myList.Start(); Console.WriteLine("The server is running at port 8888...");
            Console.WriteLine("The local End point is :" + myList.LocalEndpoint );
            Console.WriteLine("Waiting for a connection.....");
            Socket s=myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
            byte[] b=new byte[100];
            int k=s.Receive(b);
            Console.WriteLine("Recieved...");
            for (int i=0;i<k;i++) Console.Write(Convert.ToChar(b[i]));
            ASCIIEncoding asen=new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            /* clean up */
            s.Close();
            myList.Stop();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }
    }
    // * Client Program */
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Net.Sockets;
    public class clnt {
        public static void Main()
        {
            try {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");
                tcpclnt.Connect("127.0.0.1",8888);
                // use the ipaddress as in the server program
                Console.WriteLine("Connected");
                Console.Write("Enter the string to be transmitted : ");
                String str=Console.ReadLine();
                Stream stm = tcpclnt.GetStream();
                ASCIIEncoding asen= new ASCIIEncoding();
                byte[] ba=asen.GetBytes(str);
                Console.WriteLine("Transmitting.....");
                stm.Write(ba,0,ba.Length);
                byte[] bb=new byte[100];
                int k=stm.Read(bb,0,100);
                for (int i=0;i<k;i++)
                    Console.Write(Convert.ToChar(bb[i]));
                tcpclnt.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
    }
    Best Regards.


    Please click the Mark as answer button and vote as helpful if this reply solves your problem
    Friday, March 1, 2019 6:41 AM