C# chat function

This program is based on the past computer IP for chatting, and the IP can also be understood as the network management computer number, so that the network management can accurately see which machine is looking for him to chat

1. Chat interface

 

2. Declare the .net objects and announcement variables under the network management form under the form

1.public Thread td;  //声明线程对象
2.public TcpListener tcpListener;   //声明监听对象
3.private static string message = "";   //记录发送的消息

 

3. The message listening thread calls the StartListen method to monitor whether there is a message transmission with the specified port number

1.[Obsolete]
2.private void StartLinsten()
3.  {
4.        message = "";               // 清空消息
5.        tcpListener1 = new TcpListener(888);         //创建监听对象
6.        tcpListener1.Start();                //开始监听
 
7.        while (true)    //死循环+可以创建一个线程执行
8.        {
9.             TcpClient tclient = tcpListener1.AcceptTcpClient();      //接收连接请求
10.            NetworkStream nstream = tclient.GetStream();            //  获取数据流
11.            byte[] mbyet = new byte[1024];                          //建立缓存
12.            int i = nstream.Read(mbyet, 0, mbyet.Length);           //将数据流写入缓存+接 
                收实际收到的信息
13.            message = Encoding.Default.GetString(mbyet, 0, i);          //记录发送的消息  
               转为字符串
14.       }
15.  }

4. Start the timer and judge whether there is a message transmission in the Tick event of the timer. If so, display the information in the text box

1.[Obsolete]
2.private void timer1_Tick(object sender, EventArgs e)
3.{
           
4.     if (message != "")   
5.     {
6.     string[] strIP = message.Split(new char[2] { '(',')'});
7.     // comboBox1.Items.Add( str[1]);    //获取IP名
8. 
9.     string Computername= Dns.Resolve(strIP[1]).HostName;  //获取电脑名
10. 
11.     if (!comboBox1.Items.Contains(Computername))
12.      {
13.           comboBox1.Items.Add(Computername); //下拉菜单存储,对方IP的电脑名
14.      }
15. 
16.     if (message.Contains("[抖一抖]"))
17.     {
18.           Shake.Vibration(this)    //窗体抖动
19.     }
 
 
20.     rtbContent.AppendText(message);             //将接受的消息添加到文本框中   追加
21.     rtbContent.ScrollToCaret();                 //自动滚动文本框的滚动条
22.     message = "";                             //清空消息
23.     }
24.}

5. Click the "send button" to send a chat message to the designated network manager

[Obsolete]
private void button2_Click(object sender, EventArgs e)
{
       try
       {
            #region 发送消息
            IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());       //获取自己主机名
            string strmsg = " " + txtName.Text + "(" + ip[1].ToString() + ")" + DateTime.Now.ToLongTimeString() + "\n" + "" + this.rtbSend.Text + "\n";   //定义消息格式
            TcpClient client = new TcpClient(txtIP.Text, 888);   // 创建TCPClient对象
            NetworkStream netstream = client.GetStream();               //创建NetworkStream
 
            StreamWriter wstream = new StreamWriter(netstream, Encoding.Default);
            wstream.Write(strmsg);                                  //将消息写入网络流
            wstream.Flush();                                //释放网络流对象
            wstream.Close();                                    //关闭网络流对象
            client.Close();                      //关闭TCPClient
            #endregion
            //以上折叠的代码可以封装到一个类中
            //string comboitem = comboBox1.Text;
            //IPAddress[] nameToIp = Dns.GetHostAddresses(comboitem);       //获取主机名;
             
            //string strmsg = Chat.SendMessage(txtName.Text, nameToIp[1].ToString(), rtbSend.Text);
             rtbContent.AppendText(strmsg);                          //将发送的消息添加到文本框
             rtbContent.ScrollToCaret();                             //自动滚动文本框的滚动条
             rtbSend.Clear();                            //  清空发送消息文本框
 
       }
       catch (Exception ex)
       {
 
             MessageBox.Show(ex.Message);
       }
}

6. Stop the network monitoring and terminate the message monitoring thread at the same time

1.private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
2.{
3.      if (this.tcpListener1 != null)              //判断监听对象是否关闭
4.      {   
5.            tcpListener1.Stop();                     //停止监听
6.      }
7.      if (td != null)                             //判断线程是否为空
8.      {
9.            if (td.ThreadState == ThreadState.Running)          //判断线程是否正在运行中
11.            {
12.                 td.Abort();                                 //终止线程
13.            }
14.      }
15.}

 

Guess you like

Origin blog.csdn.net/yanghezheng/article/details/109542513