【问题标题】:How to receive datastream until Enter key is pressed in TCP?在 TCP 中按下 Enter 键之前如何接收数据流?
【发布时间】:2018-10-25 08:33:42
【问题描述】:

我正在创建一个 TCP 聊天室,其中多个客户端可以连接到 TCP 服务器。我能够转发我发送给所有客户的消息,但不幸的是,它会在键入时发送每一个字母,这会打乱格式。我想要的行为是仅在按下“Enter”键时发送消息。

我遇到的另一个问题是,当我询问用户名时,它只读取我键入的字符串的第一个字符作为用户名。我尝试调试它,但无法找出问题所在。以下是我发送数据和接收数据的方法。

    public void ReadData(object socket)
    {
        Socket s = (Socket)socket;

        byte[] buffer = new byte[1024];
        int k = 0;
        while (true)
        {               
            k = s.Receive(buffer);
            // event that triggers the Message() method
            SendGlobalMessage(s, buffer.GetString(k));  
        }
    }

    public void Message(Socket s, string msg)
    {
        string newMsg = String.Format("[{0}: {1}]", Connections[s], msg);
        foreach (Socket st in Connections.Keys)
        {
            st.Send(newMsg.ToByteArray());
        }
    }

请举例说明我可以采取哪些不同的做法,以便我能够牢牢把握要改变的内容。谢谢。

【问题讨论】:

  • 您不希望客户端格式化将要发送的消息,而是让服务器来做。 (String.Format("[{0}: {1}]", Connections[s], msg);)

标签: c# server client chatroom


【解决方案1】:

假设这是 WinForms

public Form1()
{
   InitializeComponent();
   textBox1.KeyPress += CheckEnterKeyPress;
}

private void CheckEnterKeyPress(object sender, KeyPressEventArgs e)
{
   if (e.KeyChar == (char)Keys.Return)
   {
      var textbox = sender as TextBox;
      Message(socket, textbox.Text);
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多