客户端:

    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使用的更多相关文章

  1. C# UdpClient使用Receive和BeginReceive接收消息时的不同写法

    使用Receive(同步阻塞方式), 注意使用同步方法时,需要使用线程来开始方法,不然会使UI界面卡死 IPEndPoint RemoteIpEndPoint = ); UdpClient udpCl ...

  2. UDPClient的用法

    UDP_Server: UdpClient receivingUdpClient = ); IPEndPoint RemoteIpEndPoint = ); try { byte[] sdata = ...

  3. Socket的三个功能类TCPClient、TCPListener 和 UDPClient (转)

    应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...

  4. C#使用 UdpClient 类进行简单通信的例子

    UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报. 因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接.但您可以选择使用下面两 ...

  5. C# UdpClient 设置超时时间

    /********************************************************************** * C# UdpClient 设置超时时间 * 说明: ...

  6. UdpClient的Connect究竟做了什么(转)

    最近在写一个音频通信的系统,因为需要还要处理其他事件,所以就自己设计底层的通信协议,用了不少底层的Socket编程(.Net Framework),搞清楚了不少细节问题. 先做一些铺垫工作.音频系统服 ...

  7. 【socket】一分钟理清 socket udpsocket tcpsocket tcplistener TCPClient和 UDPClient

    socket 套接字接口是各种语言tcp udp的网络操作的基础. 直接用socket 对象开发 可以选择 udpsocket  或者 tcpsocket ,两者在使用上仅一些方法和参数不同,所有的底 ...

  8. 【socket】Socket的三个功能类TCPClient、TCPListener 和 UDPClient

    Socket的三个功能类TCPClient.TCPListener 和 UDPClient (转) 应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制 ...

  9. uip UDPclient模式通信移植,当地port随机

    现在移植UDPclient模式,测试广播地址. //udp_client.c /************************************************************ ...

  10. uip UDPclient模式通信移植,p本地ort可以是无规

    现在移植UDPclient模式,使用广播地址检测. //udp_client.c /********************************************************** ...

随机推荐

  1. 最新 快乐阳光java校招面经 (含整理过的面试题大全)

    从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.快乐阳光等10家互联网公司的校招Offer,因为某些自身原因最终选择了快乐阳光.6.7月主要是做系统复习.项目复盘.Leet ...

  2. 使用js加载器动态加载外部js、css文件

    let MiniSite = new Object(); /** * 判断浏览器 */ MiniSite.Browser = { ie: /msie/.test(window.navigator.us ...

  3. java_guide_类加载器

    类加载器总结 JVM 中内置了三个重要的 ClassLoader,除了 BootstrapClassLoader 其他类加载器均由 Java 实现且全部继承自java.lang.ClassLoader ...

  4. 前端手势控制图片插件书写三(将transform变化应用在图片和canvas画布上)

    注意:transform的scale为负数时,图片会垂直翻转 一.在使用transform将计算得到的变化应用到图片上后,需要考虑到我们每次计算的都是touchmove中本次的差量.在第一次移动过后. ...

  5. 数据库学习其一 oracle11g数据泵导入导出

    一.检查环境一致性 需检查数据库客户端与服务端字符编码,以避免后续各种各样的问题 查询服务端编码 注意最好用sqlplus查询,用plsql有时候会出现查询不一致问题,如下图同一个语句在plsql和s ...

  6. Maven仓库介绍以及私服搭建

      1 什么是Maven? 1.1 Maven的概念 Maven主要服务于基于Java平台的项目构建.依赖管理和项目信息开发,它是一个异常强大的构建工具,能够帮助我们自动化构建过程,从清理.编译.测试 ...

  7. 虚拟机(VM)安装openwrt-koolshare软路由

    ⒈创建虚拟机 **软路由选择Windows操作系统,因为我们需要在PE环境中进行软路由的写入,固件类型选择BIOS,网络类型选择使用仅主机模式网络,虚拟磁盘类型选择IDE[一定要选择IDE模式],SC ...

  8. Linux weblogic启停

    一般weblogic启停在windows下很方便使用图标方式.但是在linux下需要杀掉weblogic进程才能真正关掉weblogic. 1.查询weblogic进程 ps -ef | grep & ...

  9. python-gitlab 统计代码行数

    需求:根据时间段,统计各个研发提交的代码行 实现逻辑:调用原生gitlab接口太复杂,引用python-gitlab 获取commit详情,然后进行统计 ======================= ...

  10. Python实现字符的冒泡排序——说实话,两个数兑换的方法震惊了我,一天比一天感受到了Python的强大

    import random M= lettList=[] for i in range(M): lettList.append(chr(random.randrange(,))) for lett i ...