C# UDP发送和接收数据

.NET C#UDP发送数据和接收数据

如图点击右侧的按钮,第一次开始监听,第二次终止监听.在监听的状态下,在左侧输入文本,点击左侧发送数据按钮,右边的文本框会显示左边发送的数据.

源码:


 
 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Net.Sockets;
  11. using System.Net;
  12. using System.Threading;
  13. namespace _02UDP通信
  14. {
  15. public partial class Form1 : Form
  16. {
  17. public Form1()
  18. {
  19. InitializeComponent();
  20. }
  21. /// <summary>
  22. /// 用于UDP发送的网络服务类
  23. /// </summary>
  24. private UdpClient udpcSend;
  25. /// <summary>
  26. /// 用于UDP接收的网络服务类
  27. /// </summary>
  28. private UdpClient udpcRecv;
  29. private void btnSend_Click(object sender, EventArgs e)
  30. {
  31. if ( string.IsNullOrWhiteSpace(txtSendMsg.Text))
  32. {
  33. MessageBox.Show( "请先输入待发送内容");
  34. return;
  35. }
  36. // 匿名发送
  37. //udpcSend = new UdpClient(0); // 自动分配本地IPv4地址
  38. // 实名发送
  39. IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse( "127.0.0.1"), 25555); // 本机IP,指定的端口号
  40. udpcSend = new UdpClient(localIpep);
  41. Thread thrSend = new Thread(SendMessage);
  42. thrSend.Start(txtSendMsg.Text);
  43. }
  44. /// <summary>
  45. /// 发送信息
  46. /// </summary>
  47. /// <param name="o"></param>
  48. void SendMessage(object o)
  49. {
  50. string message = ( string)o;
  51. byte[] sendbytes = Encoding.Unicode.GetBytes(message);
  52. IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse( "127.0.0.1"), 8848); // 发送到的IP地址和端口号
  53. udpcSend.Send(sendbytes, sendbytes.Length, remoteIpep);
  54. udpcSend.Close();
  55. ResetTextBox(txtSendMsg);
  56. }
  57. /// <summary>
  58. /// 开关:在监听UDP报文阶段为true,否则为false
  59. /// </summary>
  60. bool IsUdpcRecvStart = false;
  61. /// <summary>
  62. /// 线程:不断监听UDP报文
  63. /// </summary>
  64. Thread thrRecv;
  65. /// <summary>
  66. /// 按钮:接收数据开关
  67. /// </summary>
  68. /// <param name="sender"></param>
  69. /// <param name="e"></param>
  70. private void btnRecv_Click(object sender, EventArgs e)
  71. {
  72. if (!IsUdpcRecvStart) // 未监听的情况,开始监听
  73. {
  74. IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse( "127.0.0.1"), 8848); // 本机IP和监听端口号
  75. udpcRecv = new UdpClient(localIpep);
  76. thrRecv = new Thread(ReceiveMessage);
  77. thrRecv.Start();
  78. IsUdpcRecvStart = true;
  79. ShowMessage(txtRecvMsg, "UDP监听器已成功启动");
  80. }
  81. else // 正在监听的情况,终止监听
  82. {
  83. thrRecv.Abort(); // 必须先关闭这个线程,否则会异常
  84. udpcRecv.Close();
  85. IsUdpcRecvStart = false;
  86. ShowMessage(txtRecvMsg, "UDP监听器已成功关闭");
  87. }
  88. }
  89. /// <summary>
  90. /// 接收数据
  91. /// </summary>
  92. /// <param name="o"></param>
  93. void ReceiveMessage(object o)
  94. {
  95. IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);
  96. while ( true)
  97. {
  98. try
  99. {
  100. byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
  101. string message = Encoding.Unicode.GetString( bytRecv, 0, bytRecv.Length);
  102. ShowMessage(txtRecvMsg, string.Format( "{0}[{1}]", remoteIpep, message));
  103. }
  104. catch (Exception ex)
  105. {
  106. ShowMessage(txtRecvMsg, ex.Message);
  107. break;
  108. }
  109. }
  110. }
  111. // 向TextBox中添加文本
  112. delegate void ShowMessageDelegate(TextBox txtbox, string message);
  113. void ShowMessage(TextBox txtbox, string message)
  114. {
  115. if (txtbox.InvokeRequired)
  116. {
  117. ShowMessageDelegate showMessageDelegate = ShowMessage;
  118. txtbox.Invoke(showMessageDelegate, new object[] { txtbox, message });
  119. }
  120. else
  121. {
  122. txtbox.Text += message + "\r\n";
  123. }
  124. }
  125. // 清空指定TextBox中的文本
  126. delegate void ResetTextBoxDelegate(TextBox txtbox);
  127. void ResetTextBox(TextBox txtbox)
  128. {
  129. if (txtbox.InvokeRequired)
  130. {
  131. ResetTextBoxDelegate resetTextBoxDelegate = ResetTextBox;
  132. txtbox.Invoke(resetTextBoxDelegate, new object[] { txtbox });
  133. }
  134. else
  135. {
  136. txtbox.Text = "";
  137. }
  138. }
  139. /// <summary>
  140. /// 关闭程序,强制退出
  141. /// </summary>
  142. /// <param name="sender"></param>
  143. /// <param name="e"></param>
  144. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
  145. {
  146. Environment.Exit( 0);
  147. }
  148. }
  149. }

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用C#编写程序来发送接收UDP数据。下面是一个简单的示例代码,演示了如何发送接收UDP数据包。 首先,你需要引用System.Net命名空间,它包含了用于UDP通信的相关类。 ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { // 发送数据 UdpClient udpClient = new UdpClient(); byte[] sendData = System.Text.Encoding.ASCII.GetBytes("Hello, UDP Server!"); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("服务器IP"), 12345); udpClient.Send(sendData, sendData.Length, serverEndPoint); // 接收数据 UdpClient receivingUdpClient = new UdpClient(12345); // 绑定本地端口 IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] receivedData = receivingUdpClient.Receive(ref remoteEndPoint); string receivedMessage = System.Text.Encoding.ASCII.GetString(receivedData); Console.WriteLine("Received: " + receivedMessage); udpClient.Close(); receivingUdpClient.Close(); } } ``` 在上面的代码中,你需要将"服务器IP"替换为实际的服务器IP地址。程序首先创建一个`UdpClient`对象,该对象用于发送UDP数据包。使用`Encoding.ASCII.GetBytes`将消息转换为字节数组,并通过`Send`方法将数据包发送到指定的服务器端IP和端口。 然后,代码创建另一个`UdpClient`对象,用于接收UDP数据包。使用指定的本地端口号来监听接收的数据包。使用`Receive`方法接收数据,并使用`Encoding.ASCII.GetString`将接收到的字节数组转换为字符串。 请注意,这只是一个简单的示例,你需要根据你的实际需求进行适当的修改和错误处理。 希望这能帮到你!如果有任何其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值