客户端:

    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. Docker二

    Docker生成镜像的两种方式 有时候从Docker镜像仓库中下载的镜像不能满足要求,我们可以基于一个基础镜像构建一个自己的镜像 两种方式: 更新镜像:使用docker commit命令 构建镜像:使 ...

  2. [BAT] SetX 永久设置环境变量

    SetX 有三种使用方式: 语法 1: SETX [/S system [/U [domain\]user [/P [password]]]] var value [/M] 语法 2: SETX [/ ...

  3. ORACLE-JDK非收费版本下载链接

    这个链接下可以下载oracleJDK的所有版本 https://www.oracle.com/technetwork/java/javase/archive-139210.html 其中jdk192之 ...

  4. CG-CTF 南邮 综合题2

    个人网站 http://www.wjlshare.tk 0x00前言 主要考了三块 第一块是文件包含获取源码 第二块是通过sql绕过注入获取密码 第三块是三参数回调后门的利用 做这题的时候结合了别人的 ...

  5. 【DSP开发】帮您快速入门 TI 的 Codec Engine

    德州仪器半导体技术(上海)有限公司 通用DSP 技术应用工程师 崔晶 德州仪器(TI)的第一颗达芬奇(DaVinci)芯片(处理器)DM6446已经问世快三年了.继DM644x之后,TI又陆续推出了D ...

  6. edusoho 查找网址对应的控制器和模板页面

    刚接触这套系统的新手都在纠结模板在哪个文件里,有时候就算告诉他,遇到其他同样的模板照样还问,授人以鱼不如授人以渔!这个文章记录下我自己的看法,大爪子忽喷! 刚看到群里有人问 xxx.com/admin ...

  7. NET中的规范标准注释-- XML注释标签讲解

    一.摘要 .Net允许开发人员在源代码中插入XML注释,这在多人协作开发的时候显得特别有用. C#解析器可以把代码文件中的这些XML标记提取出来,并作进一步的处理为外部文档. 这篇文章将展示如何使用这 ...

  8. C# DataTable映射成Entity

    using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; ...

  9. Codeforces 718A Efim and Strange Grade 程序分析

    Codeforces 718A Efim and Strange Grade 程序分析 jerry的程序 using namespace std; typedef long long ll; stri ...

  10. 数据库分库分表策略之MS-SQL读写分离方案

    MS-SQL读写分离将从以下知识点进行展开: 以下截图内容来自博主:https://www.cnblogs.com/echosong/p/3603270.html 1.本地发布(写库如:centerd ...