说明
在使用 C# 开发Winform、WPF等富客户端应用程序时,有时会有 进程
之间 相互通信
的需求。
下面是一种能够实现Udp 消息收发 常用且较为简单的 C#代码。
使用注意:
- 程序退出时执行 ReleaseResources 方法,非托管资源需要及时释放.
- UdpClient类中的 Receive运行时会阻塞线程,所以需要运行在子线程上,这里使用的是由Thread类创建的线程对象.
1. 消息发送端
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace UDP
{
public class UdpClientTerminal
{
public string Ip;
public int Port;
private UdpClient udpService;
public UdpClientTerminal(string ip, int port)
{
Ip = ip; Port = port;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
udpService = new UdpClient(ep);
}
public void SendMessage(string msg, IPEndPoint ep)
{
byte[] dgram = Encoding.UTF8.GetBytes(msg);
udpService.Send(dgram, dgram.Length, ep);
}
public void ReleaseResources()
{
udpService.Close();
}
}
}
2. 消息接收端
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace UDP
{
public class UdpServerTerminal
{
public string Ip;
public int Port;
private UdpClient udpService;
private Thread threadReceive;
public UdpServerTerminal(string ip, int port)
{
Ip = ip; Port = port;
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port);
udpService = new UdpClient(ep);
threadReceive = new Thread(ReceiveMessage);
threadReceive.Start();
}
public void ReceiveMessage()
{
while (true)
{
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
byte[] data = udpService.Receive(ref remote);
string msg = Encoding.UTF8.GetString(data);
}
}
public void ReleaseResources()
{
threadReceive.Abort();
udpService.Close();
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)