简体   繁体   English

客户端服务器通信故障C#

[英]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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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