简体   繁体   中英

Client Server communication trouble C#

I created a client and server that connect to each other. The server is capable of sending the message a client sent back to the client (after processing)... however... if there are two clients connected, it only sends the message back to the client that sent the message in the first place (lol...)

How would i fix this so that it sends a message from any client to every client?

I used the example below as a starting point to get a connection between the client and server:

client server communication

when i try the following my program freezes up:

SERVER:

 private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client; 
        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 (Exception ex)
                {
                    Debug.Print(ex.Message);
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }
            }


                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                foreach (TcpClient c in ListOfClients)
                {
                System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));

                clientStream.Write(message, 0, message.Length);


            }

CLIENT:

private void boxChatArea_KeyPress(object sender, KeyPressEventArgs e)
    {
        char[] contentForServer = null;
        boxChatArea.MaxLength = 4000; 


        if (e.KeyChar == (char)Keys.Enter)
        {

            client = new TcpClient();

            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), MainWindow.port);
            client.Connect(serverEndPoint);
            clientStream = client.GetStream();


            contentForServer = boxChatArea.Text.ToCharArray();
            byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(contentForServer);
            clientStream.Write(bytesToSend, 0, bytesToSend.Length);
            clientStream.Flush();
            boxChatArea.Text = null;

            StartListening(); 

        }
    }


    public void StartListening()
    {

        HandleServerComm(client);
    }




    private void HandleServerComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        bytesRead = 0;

            try
            {
                //FREEZES HERE - it doesn't freeze here without the loop that we added within the server... 
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                //break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
            }

            if (bytesRead != 0)
            {
                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                string text = (encoder.GetString(message, 0, message.Length));

                if (enterCount >= 1)
                {
                    displayBoxChatArea.AppendText(Environment.NewLine);
                    displayBoxChatArea.AppendText(text);
                    //displayBoxChatArea.Text = text;
                    Application.DoEvents();
                }
                else
                {
                    displayBoxChatArea.Text = text;
                    Application.DoEvents();
                }
            }
        enterCount++; 
        tcpClient.Close();

    }

You should take a list of connected clients.
Try something like this:

List<TcpClient> clients = new List<TcpClient>();

private void ListenForClients()
{
     this.tcpListener.Start();

     while (true)
     {
          //blocks until a client has connected to the server
          TcpClient client = this.tcpListener.AcceptTcpClient();
          if(!clients.Contains(clients))
              clients.Add(client);
     }
}

EDITED after user comments :
You did your sending function wrong: you must first get just the message from one client, then send to everyone.

clientStream = tcpClient.GetStream(); // Not in foreach loop !!
// ...
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); 
foreach(TcpClient client in clients)
{
    // Send message to client
    st = client.GetStream();
    st.Write(message, 0, message.Length);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM