簡體   English   中英

客戶端服務器通信故障C#

[英]Client Server communication trouble C#

我創建了一個相互連接的客戶端和服務器。 服務器能夠發送客戶端發送回客戶端的消息(處理后)...但是......如果連接了兩個客戶端,它只會將消息發送回發送消息的客戶端(大聲笑...)

我如何解決這個問題,以便它從任何客戶端向每個客戶端發送消息?

我使用下面的示例作為獲取客戶端和服務器之間連接的起點:

客戶服務器通信

當我嘗試以下程序時,我的程序會凍結:

服務器:

 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);


            }

客戶:

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();

    }

您應該列出已連接的客戶端。
嘗試這樣的事情:

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);
     }
}

用戶評論后編輯
您的發送功能錯誤了:您必須先從一個客戶端獲取消息,然后發送給所有人。

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