码迷,mamicode.com
首页 > 其他好文 > 详细

Udp客户端与服务通讯

时间:2019-07-04 19:00:08      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:begin   pcl   any   bsp   ref   write   art   address   ipaddr   

使用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客户端与服务通讯

标签:begin   pcl   any   bsp   ref   write   art   address   ipaddr   

原文地址:https://www.cnblogs.com/xiaohouye/p/11134236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!