C#用UDP同步发送数据和接受数据

C#用UDP同步发送数据和接受数据

[csharp]  view plain copy
  1. using System;  
  2. using System.Text;  
  3. using System.Windows.Forms;  
  4. using System.Net;  
  5. using System.Net.Sockets;  
  6. using System.Threading;  
  7.   
  8. namespace UdpChatExample  
  9. {  
  10.     public partial class FormChat : Form  
  11.     {  
  12.         /// <summary>接收用</summary>  
  13.         private UdpClient receiveUdpClient;  
  14.         /// <summary>发送用</summary>  
  15.         private UdpClient sendUdpClient;  
  16.         /// <summary>和本机绑定的端口号</summary>  
  17.         private const int port = 18001;  
  18.         /// <summary>本机IP</summary>  
  19.         IPAddress ip;  
  20.         /// <summary>远程主机IP</summary>  
  21.         IPAddress remoteIp;  
  22.   
  23.         public FormChat()  
  24.         {  
  25.             InitializeComponent();  
  26.   
  27.             //获取本机可用IP地址  
  28.             IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());  
  29.             ip = ips[ips.Length - 1];  
  30.             //为了在同一台机器调试,此IP也作为默认远程IP  
  31.             remoteIp = ip;  
  32.             textBoxRemoteIP.Text = remoteIp.ToString();  
  33.             textBoxSend.Text = "你好!";  
  34.         }  
  35.         private void FormChat_Load(object sender, EventArgs e)  
  36.         {  
  37.             //创建一个线程接收远程主机发来的信息  
  38.             Thread myThread = new Thread(ReceiveData);  
  39.   
  40.             //将线程设为后台运行  
  41.             myThread.IsBackground = true;  
  42.             myThread.Start();  
  43.             textBoxSend.Focus();  
  44.         }  
  45.         private void ReceiveData()//接收数据  
  46.         {  
  47.             IPEndPoint local = new IPEndPoint(ip, port);  
  48.             receiveUdpClient = new UdpClient(local);  
  49.             IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);  
  50.             while (true)  
  51.             {  
  52.                 try  
  53.                 {  
  54.                     //关闭udpClient时此句会产生异常  
  55.                     byte[] receiveBytes = receiveUdpClient.Receive(ref remote);  
  56.                     string receiveMessage = Encoding.Unicode.GetString(  
  57.                         receiveBytes, 0, receiveBytes.Length);  
  58.                     AddItem(listBoxReceive, string.Format("来自{0}:{1}", remote, receiveMessage));  
  59.                 }  
  60.                 catch  
  61.                 {  
  62.                     break;  
  63.                 }  
  64.             }  
  65.         }  
  66.   
  67.         private void buttonSend_Click(object sender, EventArgs e)  
  68.         {  
  69.             Thread t = new Thread(SendMessage);//新建发送数据线程  
  70.             t.IsBackground = true;  
  71.             t.Start(textBoxSend.Text);  
  72.         }  
  73.         /// <summary>发送数据到远程主机</summary>  
  74.         private void SendMessage(object obj)  
  75.         {  
  76.             string message = (string)obj;  
  77.             sendUdpClient = new UdpClient(0);  
  78.             byte[] bytes = System.Text.Encoding.Unicode.GetBytes(message);  
  79.             IPEndPoint iep = new IPEndPoint(remoteIp, port);  
  80.             try  
  81.             {  
  82.                 sendUdpClient.Send(bytes, bytes.Length, iep);  
  83.                 AddItem(listBoxStatus, string.Format("向{0}发送:{1}", iep, message));  
  84.                 ClearTextBox();  
  85.             }  
  86.             catch (Exception ex)  
  87.             {  
  88.                 AddItem(listBoxStatus, "发送出错:" + ex.Message);  
  89.             }  
  90.         }  
  91.   
  92.         delegate void AddListBoxItemDelegate(ListBox listbox, string text);  
  93.         private void AddItem(ListBox listbox, string text)  
  94.         {  
  95.             if (listbox.InvokeRequired)  
  96.             {  
  97.                 AddListBoxItemDelegate d = AddItem;  
  98.                 listbox.Invoke(d, new object[] { listbox, text });  
  99.             }  
  100.             else  
  101.             {  
  102.                 listbox.Items.Add(text);  
  103.                 listbox.SelectedIndex = listbox.Items.Count - 1;  
  104.                 listbox.ClearSelected();  
  105.             }  
  106.         }  
  107.   
  108.         delegate void ClearTextBoxDelegate();  
  109.         private void ClearTextBox()  
  110.         {  
  111.             if (textBoxSend.InvokeRequired)  
  112.             {  
  113.                 ClearTextBoxDelegate d = ClearTextBox;  
  114.                 textBoxSend.Invoke(d);  
  115.             }  
  116.             else  
  117.             {  
  118.                 textBoxSend.Clear();  
  119.                 textBoxSend.Focus();  
  120.             }  
  121.         }  
  122.     }  
  123. }  


界面设计:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值