2022-10-18 乐帮网
c#
C#中的UdpClient使用示例,用于UDP协议的数据传输。转自于:https://www.cnblogs.com/Andren/p/4279903.html
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5858);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
while (true) //由于Receive方法是阻塞方法,一个Receive操作完了后才能继续往下执行,所以能在这里使用死循环
{
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string msg = Encoding.UTF8.GetString(receiveBytes);
}
使用BeginReceive(异步)
private static void InitializeUdpClient()
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 5858);
UdpClient udpClient = new UdpClient(RemoteIpEndPoint);
//如果这里写while(true) 则会不停挂起异步接收操作,直到占满缓冲区间或队列。会报“由于系统缓冲区空间不足或队列已满,不能执行套接字上的操作”的错
UdpState s = new UdpState(udpClient, RemoteIpEndPoint);
udpClient.BeginReceive(EndReceive, s);
}
private static void EndReceive(IAsyncResult ar)
{
try
{
UdpState s = ar.AsyncState as UdpState;
if (s != null)
{
UdpClient udpClient = s.UdpClient;
IPEndPoint ip = s.IP;
Byte[] receiveBytes = udpClient.EndReceive(ar, ref ip);
string msg = Encoding.UTF8.GetString(receiveBytes);
udpClient.BeginReceive(EndReceive, s);//在这里重新开始一个异步接收,用于处理下一个网络请求
}
}
catch (Exception ex)
{
//处理异常
}
}
public class UdpState
{
private UdpClient udpclient = null;
public UdpClient UdpClient
{
get { return udpclient; }
}
private IPEndPoint ip;
public IPEndPoint IP
{
get { return ip; }
}
public UdpState(UdpClient udpclient, IPEndPoint ip)
{
this.udpclient = udpclient;
this.ip = ip;
}
}
关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com
庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力