UDP通信小例子

服务端

 1 private void FormChat_Load(object sender, EventArgs e)
 2     {
 3         //创建接收线程
 4         Thread RecivceThread = new Thread(RecivceMsg);
 5         RecivceThread.IsBackground = true;
 6         RecivceThread.Start();
 7         sendText.Focus();
 8     }
 9 
10     private void RecivceMsg()
11     {
12         IPEndPoint local = new IPEndPoint(ip,portRecv);
13         RecviceClient = new UdpClient(local);
14 
15         IPEndPoint remote = new IPEndPoint(IPAddress.Any, portSend);
16         while (true)
17         {
18             try
19             {
20                 byte[] recivcedata =  RecviceClient.Receive(ref remote);
21                 string strMsg = Encoding.ASCII.GetString(recivcedata, 0, recivcedata.Length);
22                 AddItem(listBoxRecv, string.Format("来自{0}:{1}", remote, strMsg));
23             }
24             catch
25             {
26                 break;
27             }
28         }
29     }
View Code

客户端

 1 private void btnSend_Click(object sender, EventArgs e)
 2     {
 3         Thread t = new Thread(SendMsg);
 4         t.IsBackground = true;
 5         t.Start(sendText.Text);
 6        
 7     }
 8 
 9     private void SendMsg( object obj )
10     {
11         string message = (string)obj;
12         SendClient = new UdpClient(0);
13         byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
14         remoteIp = IPAddress.Parse(remoteIPBox.Text);
15         IPEndPoint iep = new IPEndPoint(remoteIp,portSend);
16         try
17         {
18             SendClient.Send(bytes, bytes.Length, iep);
19             AddItem(listBoxstatus, string.Format("向{0}发送:{1}", iep, message));  //异步委托显示数据
20             clearTextBox();
21         }
22         catch(Exception ex)
23         {
24             AddItem(listBoxstatus,"发送出错"+ex.Message);
25         }
26     }
View Code

 

posted @ 2020-05-05 21:06  安以痕_陈  阅读(307)  评论(0编辑  收藏  举报