【问题标题】:Client Server communication trouble C#客户端服务器通信故障C#
【发布时间】:2012-01-12 12:08:24
【问题描述】:

我创建了一个相互连接的客户端和服务器。服务器能够将客户端发回的消息发送回客户端(处理后)......但是......如果有两个客户端连接,它只会将消息发送回首先发送消息的客户端(哈哈……)

我将如何解决这个问题,以便它从任何客户端向每个客户端发送消息?

我使用下面的示例作为起点来获得客户端和服务器之间的连接:

client server communication

当我尝试以下操作时,我的程序会冻结:

服务器:

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

    }

【问题讨论】:

标签: c# .net tcp client


【解决方案1】:

您应该列出已连接的客户端。
试试这样的:

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

在用户 cmets 后编辑
你做错了你的发送功能:你必须首先从一个客户那里得到消息,然后发送给每个人。

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

【讨论】:

  • 我已经上传了我的代码,所以你可以看看我在做什么。我(认为)我已经实施了你的建议?但是,当我现在尝试发送消息时,客户端冻结..出于某种原因..
  • @BlueMonster:你能在HandleClientComm 中放置一个断点,并了解在哪一行冻结了所有内容吗?
  • 好的,我已经完成了。我将上传我的代码并放置 cmets,这样你就可以看到它在哪里发生了......
  • 嗯...仍然面临同样的问题...我已经上传了我所做的再次...也许我不明白...?
  • @BlueMonster:是的,你不明白 ;) 从 HandleClientComm 中删除 foreach 块并将其放在 Write(message) 之前,就像我编辑的帖子中一样! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多