Multiple Clients on TCPListener C# / Server sending Data

14,614

Where I am not the best with C# this post Server Client send/receive simple text how to create C# simple server, and should fix the first issue of the client not being able to recive data from the server.

As for the second issue not being able to support mulitple connections, this could be to do with there is no threading, so the question is do you want to create a C# webserver or a C# application which utilizes TCP communication to a server.

if the answer is the latter, then I would look to installing tried and tested server such a Apache or Nginx. this will allow the server to handle multiple requests on your behalf and skip having to handle multiple connections and threads, while you are learning more about the client server relationship. also this article may help setting up the fastcgi environment for the appliction http://www.mono-project.com/docs/web/fastcgi/nginx/

otherwise then you will have to look at how to handle multiple clients which this post looks like it could help TCP server with multiple Clients

Share:
14,614
Haza
Author by

Haza

Updated on June 29, 2022

Comments

  • Haza
    Haza almost 2 years

    Being a "novice" in C# and C# Network programming I tried to make a simple chat in C# using TCPClient and TCPListener , I've managed to send data from client to server but if I add a second client the server doesnt read his data and i have a second issue I couldn't figure out how to send data from server to client using TCPListener .

    Server :

        while (true)
        {
            Socket client = Server.AcceptSocket();
            Console.WriteLine("Connection accepted from " + client.RemoteEndPoint);
            count += 1;
    
            string msg;
            byte[] buf = new byte[1024];
            client.Receive(buf);
    
            msg = Encoding.UTF8.GetString(buf);
            Console.WriteLine("Received...  " + msg + "");
    
        }
    }
    

    Client :

    while (true)
            {
                Console.WriteLine("Connected");
                Console.Write("Enter the string to be transmitted : ");
    
                String msg = Console.ReadLine();
                Stream stm = tcpClient.GetStream();
    
                ASCIIEncoding asen= new ASCIIEncoding();
    
                byte[] send = asen.GetBytes(msg);
                Console.WriteLine("Transmitting.....");
                stm.Write(send, 0, send.Length);
    
                if (msg == "/Q"){
                    tcpClient.Close();
                    Environment.Exit(0);
                }
            }
    

    If you see any absurdity / Mistake in my code please tell me i'm here to learn !

    Thank You

  • Haza
    Haza about 6 years
    Thanks i will take a look at those topics .
  • Squareoot
    Squareoot about 4 years