关闭

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

1473人阅读 评论(0) 收藏 举报
分类:

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

[csharp] view plaincopy
  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. }  


界面设计:

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:362772次
    • 积分:5111
    • 等级:
    • 排名:第5407名
    • 原创:67篇
    • 转载:543篇
    • 译文:0篇
    • 评论:14条
    最新评论