• C#写一个UDP程序判断延迟并运行在Centos上


    服务端

    
    using System.Net.Sockets;
    using System.Net;
    
    
    int serverPort = 50001;
    Socket server;
    EndPoint client = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
    
    CreateSocket();
    
    void CreateSocket()
    {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPAddress ip = IPAddress.Any;
        server.Bind(new IPEndPoint(ip, serverPort));//绑定端口号和IP
        Console.WriteLine("服务端已经开启,监听端口:"+ serverPort);
        Thread t = new Thread(ReciveMsg);//开启接收消息线程
        t.Start();
    
    }
    
    /// 
    /// 接收发送给本机ip对应端口号的数据报
    /// 
    void ReciveMsg()
    {
        byte[] buffer = new byte[1024];
        byte[] sendbuffer= new byte[20];
        while (true)
        {
            
            Console.WriteLine("等待接收数据 ...");
            int length = server.ReceiveFrom(buffer, ref client);//接收数据报
            try
            {
                int no = BitConverter.ToInt32(buffer, 0);
                long getd = BitConverter.ToInt64(buffer, 4);
    
                //string message = Encoding.UTF8.GetString(buffer, 0, length);
                Console.WriteLine(client.ToString() + " : " + no + "," + getd);
    
    			int sz = 0;
                int offset = 0;
                byte[] bno = BitConverter.GetBytes(no);
                sz = 4;
                Array.Copy(bno, 0, sendbuffer,offset, sz);
                offset += sz;
                bno = BitConverter.GetBytes(getd);
                sz = 8;
                Array.Copy(bno, 0, sendbuffer, offset, sz);
           
                server.SendTo(sendbuffer, client);
            }
            catch
            {
                Console.WriteLine("error."+ client.ToString()+","+ buffer.Length.ToString());
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    在这里插入图片描述

    注意下端口号,可以使用下面的命令查看是否被占用

    netstat -alnp |grep 50001
    
    • 1

    如果没输出代表没有被使用,注意防火墙开启udp的端口

    客户端

    #define WLOG
    
    using System.Net.Sockets;
    using System.Net;
    using System.Text;
    using System.Diagnostics;
    
    string serverIp = "192.168.3.76";
    int serverPort = 50001;
    int lost = 0;   //丢包率
    long ping = 0;
    
    Socket client;
    EndPoint server;
    int sendno = 0; //连续编号
    
    
    
    int lostcount = 10;  //丢包百分比数组
    int[] losts = new int[lostcount];
    
    EndPoint recivePoint = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
    CreateClient();
    
    
    
    
    void CreateClient()
    {
        for (int i = 0; i < lostcount; i++)
            losts[i] = 1;
    
        client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        client.Bind(new IPEndPoint(IPAddress.Any, 0));
    
        server = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
    
        Thread t = new Thread(sendMsg);
        t.Start();
    
        Thread t2 = new Thread(ReciveMsg);
        t2.Start();
    }
    
    
    void Send()
    {
        //发包格式#0编号,1时间
        long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
        List<byte> byteSource = new List<byte>();
        byteSource.AddRange(BitConverter.GetBytes(sendno));
       
        byte[] tick = BitConverter.GetBytes(milliseconds);
        byteSource.AddRange(tick);
        //byte[] sendata = milliseconds.tob Encoding.UTF8.GetBytes("unity hellp");
        byte[] data = byteSource.ToArray();
    
        client.SendTo(data, server);
    
        
        losts[sendno % lostcount] = 0;
    
        sendno++;
    
        Console.WriteLine("data:"+ milliseconds.ToString()+ ",lost:"+ lost+"%");
    }
    /// 
    /// 向特定ip的主机的端口发送数据报
    /// 
    void sendMsg()
    {
    
        while (true)
        {
            Send();
            Thread.Sleep(500);
            ComputLost();
            Thread.Sleep(500);
        }
    }
    
    void ComputLost()
    {
        int all = 0;
        for (int i = 0; i < lostcount; i++)
        {
            if (losts[i] == 0)
                all++;
        }
        lost = (int)(all * 100.0 / lostcount);
    }
    
    /// 
    /// 接收发送给本机ip对应端口号的数据报
    /// 
    void ReciveMsg()
    {
        byte[] buffer = new byte[1024];
        while (true)
        {
            try
            {
                int length = client.Receive(buffer);//, ref recivePoint);//接收数据报
    
                int no = BitConverter.ToInt32(buffer, 0);
                long getd = BitConverter.ToInt64(buffer, 4);
    
               
                long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                ping = milliseconds - getd;
                losts[no % lostcount] = (int)ping+1;
               
                Console.WriteLine(recivePoint.ToString() + " , no : " + no + " , getd : " + getd + " , ping : " + ping);
            }
            catch(Exception e) 
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122

    其中ping就是发包返回的时间。lost都是发10个包丢了几个。
    在这里插入图片描述

    Centos部署

    把代码拷贝到centos目录下
    在这里插入图片描述
    如果没安装dotnet,我们安装运行时就可以了

    sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
    
    sudo yum install dotnet-runtime-7.0
    
    • 1
    • 2
    • 3

    如果直接运行,可以输入

    dotnet PingServer.dll
    
    • 1

    创建服务开机启动

    vim /etc/systemd/system/pingserver.service
    
    • 1

    内容如下

    [Unit]
    Description=pingserver for centos7
    
    [Service]
    WorkingDirectory=/home/pingserver/Release
    ExecStart=/usr/bin/dotnet /home/pingserver/Release/PingServer.dll
    Restart=always
    RestartSec=10  # Restart service after 10 seconds if dotnet service crashes
    SyslogIdentifier=dotnet-pingserver
    User=root
    Environment=ASPNETCORE_ENVIRONMENT=Production
    Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
    
    [Install]
    WantedBy=multi-user.target
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    可以设置开机启动

    systemctl enable pingserver.service
    
    • 1

    开启和状态

    systemctl start pingserver.service
    systemctl stop pingserver.service
    systemctl status pingserver.service
    
    • 1
    • 2
    • 3

    查看运行日志可以

    journalctl -u pingserver.service
    
    显示最近20条
    journalctl -u pingserver -n 20
    
    还可以通过其他参数显示需要的,journalctl --help
    例如从某个时间开始 
    journalctl -u pingserver -S "2023-10-27 11:30:00"
    journalctl -u pingserver -S "11:30:00"
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注意配置文件如果在windows下编辑,记得换行符要改成LF(unix)格式的utf8才可以。

  • 相关阅读:
    Rust和Pytho写一段采集公众号代码
    EDID详解
    每日一题44:合作过至少三次的演员和导演
    万应案例精选|抓紧抓实抓细,万应为安全生产全域监管护航
    小学单位换算表大全
    计算机毕业设计之java+ssm校园视频监控系统
    QML插件的制作与应用
    mysql 数据库迁移
    ST表倒序释放:1019T1
    Java-GUI编程之事件处理
  • 原文地址:https://blog.csdn.net/thinbug/article/details/132743400