zoukankan      html  css  js  c++  java
  • 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();
    }
    }

  • 相关阅读:
    影视-纪录片:《梵净山》
    NuGet:ServiceStack
    资源-产品:ServiceStack
    Win7x64安装Oracle11201x64 解决PLSQL Developer无法找到oci问题
    Oracle11g环境设置-windows环境
    安装sql server提示挂起报错
    安装oracle11g未找到文件WFMLRSVCApp.ear文件
    配置linux中文
    卸载rpm包提示:error: specifies multiple packages
    FileZilla简单介绍及运用
  • 原文地址:https://www.cnblogs.com/xiaohouye/p/11134236.html
Copyright © 2011-2022 走看看