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

news/2024/5/18 15:29:21 标签: 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();

}

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

在这里插入图片描述

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

netstat -alnp |grep 50001

如果没输出代表没有被使用,注意防火墙开启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+"%");
}
/// <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,我们安装运行时就可以了

sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm

sudo yum install dotnet-runtime-7.0

如果直接运行,可以输入

dotnet PingServer.dll

创建服务开机启动

vim /etc/systemd/system/pingserver.service

内容如下

[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

可以设置开机启动

systemctl enable pingserver.service

开启和状态

systemctl start pingserver.service
systemctl stop pingserver.service
systemctl status pingserver.service

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


http://www.niftyadmin.cn/n/5016520.html

相关文章

vue制作页面水印

1.新建一个js js的代码 let watermark {}let setWatermark (str) > {let id 1.23452384164.123412415if (document.getElementById(id) ! null) {document.body.removeChild(document.getElementById(id))}let can document.createElement(canvas)can.width 500can.he…

Sui Lutris:Sui核心的分布式系统协议

经过数个月的测试&#xff0c;Mysten Labs于 8月18日更新了Sui Lutris白皮书&#xff0c;确定了以下内容&#xff1a; 使用PTBs和5K TPS&#xff0c;Sui每秒可以处理140k至150k次操作&#xff0c;这表明Sui在主网峰值&#xff08;约700 TPS&#xff09;下的基准测试远低于其实…

Linux 进程管理之内核栈和struct pt_regs

文章目录 前言一、内核栈二、struct pt_regs2.1 简介2.2 获取pt_regs 参考资料 前言 Linux内核栈是用于存储内核执行期间的函数调用和临时数据的一块内存区域。每个运行的进程都有自己的内核栈&#xff0c;用于处理中断、异常、系统调用以及内核函数的执行。 每个进程的内核栈…

Java 若依框架导出excel添加单表头标题

图示 若依框架通过Excel注解已经封装好导出的工具类了&#xff0c;目前是可以实现简单的单表表头标题添加 在exportExcel方法的后面直接添加一项参数就可以导出添加标题了~

浅谈redis未授权漏洞

redis未授权漏洞 利用条件 版本比较高的redis需要修改redis的配置文件&#xff0c;将bind前面#注释符去掉&#xff0c;将protected-mode 后面改为no 写入webshell config get dir #查看redis数据库路径 config set dir web路径# #修改靶机Redis数据库路径 config set dbfilen…

Xilinx IDDR与ODDR原语的使用

文章目录 ODDR原语1. OPPOSITE_EDGE 模式2. SAME_EDGE 模式 ODDR原语 例化模板&#xff1a; ODDR #(.DDR_CLK_EDGE("OPPOSITE_EDGE"), // "OPPOSITE_EDGE" or "SAME_EDGE" .INIT(1b0), // Initial value of Q: 1b0 or 1b1.SRTYPE("SYNC…

【C++从入门到精通】第1篇:C++基础知识(上)

文章目录 1.1 C语句和程序结构1.1.1 本篇介绍1.1.2 语句1.1.3 函数和主函数1.1.4 解析Hello world1.1.5 语法和语法错误1.1.6 练习时间 1.2 注释1.2.1 单行注释1.2.2 多行注释1.2.3 正确使用注释1.2.4 注释掉代码 1.3 对象和变量1.3.1 数据和值1.3.2 对象和变量1.3.3 变量实例化…

数学分析:势场

首先从散度的物理解释开始。首先&#xff0c;在球内的向量场的散度的积分&#xff0c;等于它在球边界上的流量的积分。所以根据积分中值定理&#xff0c;我们可以这么理解散度&#xff0c;它就是这个体积内的速度场的平均密度。而速度场只和源有关&#xff0c;所以它表示的某个…