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

  • 相关阅读:
    压缩感知的由来
    VS2010自动崩溃问题
    随机过程好书推荐
    Kernel PCA
    稀疏性与L1范数
    豆瓣关于计算机视觉的书评及介绍
    压缩感知测量矩阵的研究现状(转)
    信号的功率谱、能量谱、频谱的区别(转)
    vc++ & matlab 换行符号
    arg min 的含义
  • 原文地址:https://www.cnblogs.com/xiaohouye/p/11134236.html
Copyright © 2011-2022 走看看