4

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
  • 97
  • 1
  • 2
  • 10
  • I think this is not a duplicate of the question on sending JSON serialized data through TCP. Although that question contains a complete example on TCP communication, this question could be answered by fixing OP's misconceptions and mistakes which are visible from the code. – Sorashi Apr 08 '18 at 17:26
  • Now that I think of it, this question would fit in CodeReview, but marking it as a duplicate of the first TCP-related question found by the moderator is wrong imo. I'd suggest the OP to appeal. – Sorashi Apr 08 '18 at 17:50

1 Answers1

4

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