基于c#用Socket做一个局域网聊天工具

2019-12-30 14:18:58王冬梅

如果按下发送消息的按钮, 则发送txtSendMsg中的文本, 我写的是用Unicode编码, 所以可以发送中文字符.


private void btnSendMsg_Click(object sender, EventArgs e)
{
  string input = txtSendMsg.Text;
  if (input == "")
  {
    MessageBox.Show("消息不能为空!", "发送消息出错");
    txtSendMsg.Focus();
  }
  else
  {
    if (meIsClient)
    {
      newclient.Send(Encoding.Unicode.GetBytes(input));
      string showText = "Me:      " + System.DateTime.Now.ToString() + "n  "
      + input + "n";
      int txtGetMsgLength = txtGetMsg.Text.Length;
      txtGetMsg.AppendText(showText);
      txtGetMsg.Select(txtGetMsgLength, showText.Length - 1 - input.Length);
      txtGetMsg.SelectionColor = Color.Blue;
      txtSendMsg.Text = "";
    }
    else
    {
      client.Send(Encoding.Unicode.GetBytes(input));
      string showText = "Me    " + System.DateTime.Now.ToString() + "n  "
      + input + "n";
      int txtGetMsgLength = txtGetMsg.Text.Length;
      txtGetMsg.AppendText(showText);
      txtGetMsg.Select(txtGetMsgLength, showText.Length - 1 - input.Length);
      txtGetMsg.SelectionColor = Color.Blue;
      txtSendMsg.Text = "";
    }
  }
}

程序的运行效果:

socket聊天程序,c#局域网聊天程序,c#socket,聊天

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到c#教程频道。