关闭

C#用UDP异步发送信息

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

C#用UDP异步发送信息

[csharp] view plaincopy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8.   
  9. //添加的命名空间引用  
  10. using System.Net;  
  11. using System.Net.Sockets;  
  12. using System.Threading;  
  13.   
  14. namespace AsyncUdpChatExample  
  15. {  
  16.     public partial class FormAsyncChat : Form  
  17.     {  
  18.           
  19.         AddListBoxItemCallback listBoxCallback;  
  20.         //使用的接收端口号  
  21.         private int port = 8001;  
  22.         //接收信息用UdpClient实例  
  23.         UdpClient receiveClient;  
  24.         IPEndPoint iep;  
  25.         String sendMessage;  
  26.         public FormAsyncChat()  
  27.         {  
  28.             InitializeComponent();  
  29.             listBoxCallback = new AddListBoxItemCallback(AddListBoxItem);  
  30.         }  
  31.   
  32.         /// <summary>  
  33.         /// 初始化窗体  
  34.         /// </summary>  
  35.         /// <param name="sender"></param>  
  36.         /// <param name="e"></param>  
  37.         private void FormChat_Load(object sender, EventArgs e)  
  38.         {  
  39.             //设置listBox样式  
  40.             listBoxReceive.HorizontalScrollbar = true;  
  41.             listBoxReceive.Dock = DockStyle.Fill;  
  42.             //获取本机第一个可用IP地址  
  43.             IPAddress myIP = (IPAddress)Dns.GetHostAddresses(Dns.GetHostName()).GetValue(1);  
  44.             //为了在同一台机器调试,此IP也作为默认远程IP  
  45.             textBoxRemoteIP.Text = myIP.ToString();  
  46.             receiveClient = new UdpClient(port);  
  47.   
  48.             //创建一个线程接收远程主机发来的信息  
  49.             Thread myThread = new Thread(ReceiveData);  
  50.             //将线程设为后台运行  
  51.             myThread.IsBackground = true;  
  52.             myThread.Start();  
  53.             textBoxSend.Focus();  
  54.         }  
  55.           
  56.         /// <summary>  
  57.         /// 在后台运行的接收线程  
  58.         /// </summary>  
  59.         private void ReceiveData()  
  60.         {  
  61.             //在本机指定的端口接收  
  62.             UdpState udpState = new UdpState();  
  63.             udpState.IpEndPoint = null;  
  64.             udpState.MyudpClient = receiveClient;  
  65.             //接收从远程主机发送过来的信息;  
  66.             IAsyncResult ar =  udpState.MyudpClient.BeginReceive(ReceiveUdpClientCallback, udpState);  
  67.             ar.AsyncWaitHandle.WaitOne();  
  68.             Console.Write("线程结束");  
  69.         }  
  70.   
  71.         /// <summary>  
  72.         /// 接收信息回调方法  
  73.         /// </summary>  
  74.         /// <param name="ar"></param>  
  75.         void ReceiveUdpClientCallback(IAsyncResult ar)  
  76.         {  
  77.             try  
  78.             {  
  79.                 UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).MyudpClient;  
  80.                 IPEndPoint remote = (IPEndPoint)((UdpState)(ar.AsyncState)).IpEndPoint;  
  81.                 Byte[] receiveBytes = u.EndReceive(ar, ref remote);  
  82.                 string str = Encoding.UTF8.GetString(receiveBytes, 0, receiveBytes.Length);  
  83.                 AddItem(listBoxReceive, string.Format("来自{0}:{1}", remote, str));  
  84.                 ReceiveData();//继续接受数据  
  85.             }  
  86.             catch (Exception ex)  
  87.             {  
  88.                 AddItem(listBoxReceive, string.Format("错误信息{0}", ex.ToString()));  
  89.             }  
  90.         }  
  91.         /// <summary>  
  92.         /// 发送数据到远程主机  
  93.         /// </summary>  
  94.         private void sendData()  
  95.         {  
  96.             UdpClient sendUdpClient = new UdpClient();  
  97.             IPAddress remoteIP;  
  98.             if (IPAddress.TryParse(textBoxRemoteIP.Text, out remoteIP) == false)  
  99.             {  
  100.                 MessageBox.Show("远程IP格式不正确");  
  101.                 return;  
  102.             }  
  103.             iep = new IPEndPoint(remoteIP, port);  
  104.             sendMessage = textBoxSend.Text;  
  105.             byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sendMessage);  
  106.             try  
  107.             {  
  108.                 //异步发送数据  
  109.                 IAsyncResult ar=  
  110.                 sendUdpClient.BeginSend(bytes, bytes.Length, iep, SendCallback, sendUdpClient);//sendUdpClient是传给回调函数SendCallback的参数  
  111.                   
  112.                 textBoxSend.Clear();  
  113.                 textBoxSend.Focus();  
  114.             }  
  115.             catch (Exception err)  
  116.             {  
  117.                 MessageBox.Show(err.Message, "发送失败");  
  118.             }  
  119.         }  
  120.   
  121.         /// </summary>  
  122.         /// <param name="ar">IAsyncResult接口</param>  
  123.         public void SendCallback(IAsyncResult ar)  
  124.         {  
  125.             UdpClient udpClient = (UdpClient)ar.AsyncState;  
  126.             udpClient.EndSend(ar);  
  127.             String message = string.Format("向{0}发送:{1}", iep.ToString(), sendMessage);  
  128.             AddItem(listBoxStatus, message);  
  129.             udpClient.Close();  
  130.         }  
  131.           
  132.         /// <summary>  
  133.         /// 单击发送按钮触发的事件  
  134.         /// </summary>  
  135.         private void buttonSend_Click(object sender, EventArgs e)  
  136.         {  
  137.             sendData();  
  138.         }  
  139.         /// <summary>  
  140.         /// 在textBoxSend中按下并释放Enter键后触发的事件  
  141.         /// </summary>  
  142.         private void textBoxData_KeyPress(object sender, KeyPressEventArgs e)  
  143.         {  
  144.             if (e.KeyChar == (char)Keys.Enter)  
  145.                 sendData();  
  146.         }  
  147.         /// <summary>  
  148.         /// 关闭窗体,释放资源  
  149.         /// </summary>  
  150.         /// <param name="sender"></param>  
  151.         /// <param name="e"></param>  
  152.         private void FormChat_FormClosing(object sender, FormClosingEventArgs e)  
  153.         {  
  154.             receiveClient.Close();  
  155.         }  
  156.           
  157.         delegate void AddListBoxItemDelegate(ListBox listbox, string text);  
  158.         private void AddItem(ListBox listbox, string text)  
  159.         {  
  160.             if (listbox.InvokeRequired)  
  161.             {  
  162.                 AddListBoxItemDelegate d = AddItem;  
  163.                 listbox.Invoke(d, new object[] { listbox, text });  
  164.             }  
  165.             else  
  166.             {  
  167.                 listbox.Items.Add(text);  
  168.                 listbox.SelectedIndex = listbox.Items.Count - 1;  
  169.                 listbox.ClearSelected();  
  170.             }  
  171.         }  
  172.   
  173.         delegate void ClearTextBoxDelegate();  
  174.         private void ClearTextBox()  
  175.         {  
  176.             if (textBoxSend.InvokeRequired)  
  177.             {  
  178.                 ClearTextBoxDelegate d = ClearTextBox;  
  179.                 textBoxSend.Invoke(d);  
  180.             }  
  181.             else  
  182.             {  
  183.                 textBoxSend.Clear();  
  184.                 textBoxSend.Focus();  
  185.             }  
  186.         }  
  187.   
  188.         delegate void AddListBoxItemCallback(string text);  
  189.         private void AddListBoxItem(string text)  
  190.         {  
  191.             //如果listBoxReceive被不同的线程访问则通过委托处理;  
  192.             if (listBoxReceive.InvokeRequired)  
  193.             {  
  194.                 this.Invoke(listBoxCallback, text);  
  195.             }  
  196.             else  
  197.             {  
  198.                 listBoxReceive.Items.Add(text);  
  199.                 listBoxReceive.SelectedIndex = listBoxReceive.Items.Count - 1;  
  200.                 listBoxReceive.ClearSelected();  
  201.             }  
  202.         }  
  203.     }  
  204. }  

界面设计:

0
0

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