C# UdpClient使用
客户端:
public class UdpClientManager
{
//接收数据事件
public Action<string> recvMessageEvent = null;
//发送结果事件
public Action<int> sendResultEvent = null;
//本地监听端口
public int localPort = 0; private UdpClient udpClient = null; public UdpClientManager(int localPort)
{
if (localPort < 0 || localPort > 65535)
throw new ArgumentOutOfRangeException("localPort is out of range"); this.localPort = localPort;
} public void Start()
{
while (true)
{
try
{
udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);//指定本地监听port
ReceiveMessage();
break;
}
catch (Exception)
{
Thread.Sleep(100);
}
}
} private async void ReceiveMessage()
{
while (true)
{
if (udpClient == null)
return; try
{
UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
if (recvMessageEvent != null)
recvMessageEvent(message);
}
catch (Exception ex)
{
}
}
} //单播
public async void SendMessageByUnicast(string message, string destHost, int destPort)
{
if (string.IsNullOrEmpty(message))
throw new ArgumentNullException("message cant not null");
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null");
if (string.IsNullOrEmpty(destHost))
throw new ArgumentNullException("destHost cant not null");
if (destPort < 0 || destPort > 65535)
throw new ArgumentOutOfRangeException("destPort is out of range"); byte[] buffer = Encoding.UTF8.GetBytes(message);
int len = 0;
for (int i = 0; i < 3; i++)
{
try
{
len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(destHost), destPort));
}
catch (Exception)
{
len = 0;
} if (len <= 0)
Thread.Sleep(100);
else
break;
} if (sendResultEvent != null)
sendResultEvent(len);
} public void CloseUdpCliend()
{
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); try
{
udpClient.Client.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
udpClient.Close();
udpClient = null;
}
}
服务器:
public class UdpServiceManager
{
private readonly string broadCastHost = "255.255.255.255";
//接收数据事件
public Action<string> recvMessageEvent = null;
//发送结果事件
public Action<int> sendResultEvent = null;
//本地host
private string localHost = "";
//本地port
private int localPort = 0; private UdpClient udpClient = null; public UdpServiceManager(string localHost, int localPort)
{
if (string.IsNullOrEmpty(localHost))
throw new ArgumentNullException("localHost cant not null");
if (localPort < 0 || localPort > 65535)
throw new ArgumentOutOfRangeException("localPort is out of range"); this.localHost = localHost;
this.localPort = localPort;
} public void Start()
{
while (true)
{
try
{
udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(localHost), localPort));//绑定本地host和port
ReceiveMessage();
break;
}
catch (Exception)
{
Thread.Sleep(100);
}
}
} private async void ReceiveMessage()
{
while (true)
{
if (udpClient == null)
return; try
{
UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
if (recvMessageEvent != null)
recvMessageEvent(message);
}
catch (Exception)
{
}
}
} //单播
public async void SendMessageByUnicast(string message, string destHost, int destPort)
{
if (string.IsNullOrEmpty(message))
throw new ArgumentNullException("message cant not null");
if (string.IsNullOrEmpty(destHost))
throw new ArgumentNullException("destHost cant not null");
if (destPort < 0 || destPort > 65535)
throw new ArgumentOutOfRangeException("destPort is out of range");
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); byte[] buffer = Encoding.UTF8.GetBytes(message);
int len = 0;
for (int i = 0; i < 3; i++)
{
try
{
len = await udpClient.SendAsync(buffer, buffer.Length, destHost, destPort);
}
catch (Exception)
{
len = 0;
} if (len <= 0)
Thread.Sleep(100);
else
break;
} if (sendResultEvent != null)
sendResultEvent(len);
} //广播
public async void SendMessageByBroadcast(string message)
{
if (string.IsNullOrEmpty(message))
throw new ArgumentNullException("message cant not null");
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); byte[] buffer = Encoding.UTF8.GetBytes(message);
int len = 0;
for (int i = 0; i < 3; i++)
{
try
{
len = await udpClient.SendAsync(buffer, buffer.Length, broadCastHost, localPort);
}
catch (Exception ex)
{
len = 0;
} if (len <= 0)
Thread.Sleep(100);
else
break;
} if (sendResultEvent != null)
sendResultEvent(len);
} public void CloseUdpCliend()
{
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); try
{
udpClient.Client.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
udpClient.Close();
udpClient = null;
}
}
多播方式
public class UdpClientManager
{
//接收数据事件
public Action<string> recvMessageEvent = null;
//发送结果事件
public Action<int> sendResultEvent = null;
//本地监听端口
public int localPort = 0;
//组播地址
public string MultiCastHost = ""; private UdpClient udpClient = null; public UdpClientManager(int localPort, string MultiCastHost)
{
if (localPort < 0 || localPort > 65535)
throw new ArgumentOutOfRangeException("localPort is out of range");
if (string.IsNullOrEmpty(MultiCastHost))
throw new ArgumentNullException("message cant not null"); this.localPort = localPort;
this.MultiCastHost = MultiCastHost;
} public void Start()
{
while (true)
{
try
{
udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);//指定本地监听port
udpClient.JoinMulticastGroup(IPAddress.Parse(MultiCastHost));
ReceiveMessage();
break;
}
catch (Exception)
{
Thread.Sleep(100);
}
}
} private async void ReceiveMessage()
{
while (true)
{
if (udpClient == null)
return; try
{
UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
if (recvMessageEvent != null)
recvMessageEvent(message);
}
catch (Exception ex)
{
}
}
} public async void SendMessageByMulticast(string message)
{
if (string.IsNullOrEmpty(message))
throw new ArgumentNullException("message cant not null");
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); byte[] buffer = Encoding.UTF8.GetBytes(message);
int len = 0;
for (int i = 0; i < 3; i++)
{
try
{
len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(MultiCastHost), localPort));
}
catch (Exception)
{
len = 0;
} if (len <= 0)
Thread.Sleep(100);
else
break;
} if (sendResultEvent != null)
sendResultEvent(len);
} public void CloseUdpCliend()
{
if (udpClient == null)
throw new ArgumentNullException("udpClient cant not null"); try
{
udpClient.Client.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
}
udpClient.Close();
udpClient = null;
}
}
C# UdpClient使用的更多相关文章
- C# UdpClient使用Receive和BeginReceive接收消息时的不同写法
使用Receive(同步阻塞方式), 注意使用同步方法时,需要使用线程来开始方法,不然会使UI界面卡死 IPEndPoint RemoteIpEndPoint = ); UdpClient udpCl ...
- UDPClient的用法
UDP_Server: UdpClient receivingUdpClient = ); IPEndPoint RemoteIpEndPoint = ); try { byte[] sdata = ...
- Socket的三个功能类TCPClient、TCPListener 和 UDPClient (转)
应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...
- C#使用 UdpClient 类进行简单通信的例子
UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报. 因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接.但您可以选择使用下面两 ...
- C# UdpClient 设置超时时间
/********************************************************************** * C# UdpClient 设置超时时间 * 说明: ...
- UdpClient的Connect究竟做了什么(转)
最近在写一个音频通信的系统,因为需要还要处理其他事件,所以就自己设计底层的通信协议,用了不少底层的Socket编程(.Net Framework),搞清楚了不少细节问题. 先做一些铺垫工作.音频系统服 ...
- 【socket】一分钟理清 socket udpsocket tcpsocket tcplistener TCPClient和 UDPClient
socket 套接字接口是各种语言tcp udp的网络操作的基础. 直接用socket 对象开发 可以选择 udpsocket 或者 tcpsocket ,两者在使用上仅一些方法和参数不同,所有的底 ...
- 【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient
Socket的三个功能类TCPClient.TCPListener 和 UDPClient (转) 应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制 ...
- uip UDPclient模式通信移植,当地port随机
现在移植UDPclient模式,测试广播地址. //udp_client.c /************************************************************ ...
- uip UDPclient模式通信移植,p本地ort可以是无规
现在移植UDPclient模式,使用广播地址检测. //udp_client.c /********************************************************** ...
随机推荐
- Leetcode之动态规划(DP)专题-474. 一和零(Ones and Zeroes)
Leetcode之动态规划(DP)专题-474. 一和零(Ones and Zeroes) 在计算机界中,我们总是追求用有限的资源获取最大的收益. 现在,假设你分别支配着 m 个 0 和 n 个 1. ...
- lua程序设计 第一章习题答案
练习1.1:运行阶乘的示例并观察,如果输入负数,程序会出现什么问题?试着修改代码来解决问题. 答:当输入负数时,循环无法终止,因为原本程序中的终止条件为n==0,而在输入为负数情况下,无法达成此终止条 ...
- 第35课.函数对象分析("()"重载)
1.编写一个函数 a.函数可以获得斐波那契数列 b.每调一次返回一个值 c.函数可以根据需要重复使用 2.函数数对象 a.使用具体的类对象取代函数 b.改类的对象具备函数调用的行为 c.构造函数指具体 ...
- eNSP——配置Trunk接口
原理: 在以太网中,通过划分 VLAN 来隔离广播域和增强网络通信的安全性.以太网通常由多台交换机组成,为了使 VLAN 的数据帧跨越多台交换机传递,交换机之间互连的链路需要设置为干道链路( Trun ...
- [LuoguP2159][SHOI2009]舞会_动态规划_高精度_排列组合
舞会 题目链接:https://www.luogu.org/problem/P2159 数据范围:略. 题解: 不会.... 看了题解觉得自己好傻逼啊
- superset部署
superset功能概述: 丰富的数据可视化集 易于使用的界面,用于探索和可视化数据 创建和共享仪表板 与主要身份验证提供程序集成的企业级身份验证(通过Flask AppBuilder进行数据库,Op ...
- 【AtCoder】AGC004
AGC004 A - Divide a Cuboid 看哪一维是偶数,答案是0,否则是三个数两两组合相乘中最小的那个 #include <bits/stdc++.h> #define fi ...
- Do Not Try This Problem(分块思想)
题意:https://codeforces.com/group/ikIh7rsWAl/contest/259944/problem/D 给你q个操作,4个数n,a,k,c,从n好位置开始每次加a的位置 ...
- unittest参数化(paramunittest)
前言 paramunittest是unittest实现参数化的一个专门的模块,可以传入多组参数,自动生成多个用例前面讲数据驱动的时候,用ddt可以解决多组数据传入,自动生成多个测试用例.本篇继续介绍另 ...
- linux tcp listen函数的参数backlog
1 listen函数(http://man7.org/linux/man-pages/man2/listen.2.html) int listen(int sockfd, int backlog); ...