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

服务端

csharp 复制代码
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();

}

/// <summary>
/// 接收发送给本机ip对应端口号的数据报
/// </summary>
void ReciveMsg()
{
    byte[] buffer = new byte[1024];
    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);

            server.SendTo(buffer, client);
        }
        catch
        {
            Console.WriteLine("error."+ client.ToString()+","+ buffer.Length.ToString());
        }
    }
}

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

bash 复制代码
netstat -alnp |grep 50001

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

客户端

csharp 复制代码
#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+"%");
}
/// <summary>
/// 向特定ip的主机的端口发送数据报
/// </summary>
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);
}

/// <summary>
/// 接收发送给本机ip对应端口号的数据报
/// </summary>
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());
        }
    }
}

其中ping就是发包返回的时间。lost都是发10个包丢了几个。

在Centos部署

把代码拷贝到centos目录下

如果没安装dotnet,我们安装运行时就可以了

bash 复制代码
sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm

sudo yum install dotnet-runtime-7.0

如果直接运行,可以输入

bash 复制代码
dotnet PingServer.dll

创建服务开机启动

bash 复制代码
vim /etc/systemd/system/pingserver.service

内容如下

bash 复制代码
[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

可以设置开机启动

bash 复制代码
systemctl enable pingserver.service

开启和状态

bash 复制代码
systemctl start pingserver.service
systemctl stop pingserver.service
systemctl status pingserver.service

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

相关推荐
千天夜12 分钟前
使用UDP协议传输视频流!(分片、缓存)
python·网络协议·udp·视频流
Ven%2 小时前
centos查看硬盘资源使用情况命令大全
linux·运维·centos
IT技术分享社区2 小时前
C#实战:使用腾讯云识别服务轻松提取火车票信息
开发语言·c#·云计算·腾讯云·共识算法
上辈子杀猪这辈子学IT3 小时前
【Zookeeper集群搭建】安装zookeeper、zookeeper集群配置、zookeeper启动与关闭、zookeeper的shell命令操作
linux·hadoop·zookeeper·centos·debian
minihuabei3 小时前
linux centos 安装redis
linux·redis·centos
△曉風殘月〆9 小时前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm
逐·風11 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
m0_6569747414 小时前
C#中的集合类及其使用
开发语言·c#
九鼎科技-Leo14 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo17 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net