Udp客户端与服务通讯
Posted xiaohouye
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Udp客户端与服务通讯相关的知识,希望对你有一定的参考价值。
使用UDP与服务端通讯时候,同样需要先启用udp服务端监控,当服务端启动成功,在启动客户端
首先UDP服务端类,代码如下:
public class UdpServerTest
public void BeginUdpServer()
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//接收数据
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//关闭连接
2.ddp客户端代码如下:
public class UdpClientTest
public void BeginUdpClient()
string sendString = null;//要发送的字符串
byte[] sendData = null;//要发送的字节数组
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点
while (true)
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点
client.Close();//关闭连接
3.测试代码如下:
a.启动UDP服务端代码:
private static void startServer()
UdpServerTest test = new UdpServerTest();
Task.Run(() =>
test.BeginUdpServer();
);
b.启用UDP客户端代码如下
class Program
static void Main(string[] args)
UdpClientTest client = new UdpClientTest();
client.BeginUdpClient();
以上是关于Udp客户端与服务通讯的主要内容,如果未能解决你的问题,请参考以下文章
MicroPython ESP32 UDP和TCP数据收发通讯综合实例