zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    MyBatis Sql Session 批量插入
    Node.js 之react.js组件-Props应用
    Node.js 之react.js组件-JSX简介
    Node.js项目笔记(一)
    2020软件工程个人作业06——软件工程实践总结作业
    2020软件工程作业05
    2020软件工程作业00——问题清单
    2020软件工程作业04
    2020软件工程作业03
    2020软件工程作业02
  • 原文地址:https://www.cnblogs.com/anyihen/p/12832739.html
Copyright © 2011-2022 走看看