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();
}
}

猜你喜欢

转载自www.cnblogs.com/xiaohouye/p/11134236.html