当前位置: 首页 > news >正文

在树莓派上用 .NET8.0 挂载TCP服务端

目录

1.TCP服务端开发

2.部署环境

3.创建服务

4.测试连接


1.TCP服务端开发

 创建控制台程序,选择.NET 8.0框架

运行时启动TCP服务监听

using LS.Standard.Helper.Logs;
using UpdateServer;LogOperate.InitLog(1, AppDomain.CurrentDomain.BaseDirectory + "Logs\\");
TCP_Server.Start();while (true)
{string res = Console.ReadLine();if (res == "quit"){break;}
}

TCP服务端实现:

监听端口 13000

接收到消息,就原路返回处理的结果。

using System.Net;
using System.Net.Sockets;
using System.Text;namespace UpdateServer
{public static class TCP_Server{private static readonly List<TcpClient> _connectedClients = new();private static readonly object _lock = new();public static async Task Start(){const int port = 13000;TcpListener listener = new TcpListener(IPAddress.Any, port);listener.Start();Console.WriteLine($"TCP Server started. Listening on port {port}...");try{while (true){// 异步接收客户端连接TcpClient client = await listener.AcceptTcpClientAsync();lock (_lock){_connectedClients.Add(client);}// 为每个客户端启动独立处理任务_ = Task.Run(() => HandleClientAsync(client));}}catch (Exception ex){Console.WriteLine($"Server fatal error: {ex.Message}");}}private static async Task HandleClientAsync(TcpClient client){string clientId = client.Client.RemoteEndPoint?.ToString() ?? "Unknown";Console.WriteLine($"Client connected: {clientId}");try{using NetworkStream stream = client.GetStream();byte[] buffer = new byte[4096];while (client.Connected){// 异步读取数据int bytesRead = await stream.ReadAsync(buffer);if (bytesRead == 0) continue;string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);//消息处理switch (message){case "UpdateServer":string res = UpdateExecute.Check();var data = Encoding.UTF8.GetBytes(res);SendToClientAsync(client, data);if (res == "OK"){//开始执行更新程序Task.Run(UpdateExecute.Execute);}break;}}}catch (IOException ex) when (ex.InnerException is SocketException se){Console.WriteLine($"Client {clientId} disconnected abruptly: {se.SocketErrorCode}");}finally{lock (_lock){_connectedClients.Remove(client);}client.Dispose();Console.WriteLine($"Client disconnected: {clientId}");}}// 广播消息给所有连接的客户端private static async Task BroadcastMessageAsync(string message){byte[] data = Encoding.UTF8.GetBytes(message);List<Task> sendTasks = new();lock (_lock){foreach (var client in _connectedClients.Where(c => c.Connected)){sendTasks.Add(SendToClientAsync(client, data));}}await Task.WhenAll(sendTasks);}private static async Task SendToClientAsync(TcpClient client, byte[] data){try{await client.GetStream().WriteAsync(data);}catch (Exception ex){Console.WriteLine($"Send error to {client.Client.RemoteEndPoint}: {ex.Message}");}}}
}

2.部署环境

下载.NET 8.0的SDK

复制到树莓派上,我这边使用的地址是:/home/administrator/dotnetFile/

放上去之后,可以使用名称检测库文件是否可用:

sudo /home/administrator/dotnetFile/dotnet --info

然后再将控制台程序文件拷贝上去

这边使用的目录是:/home/administrator/UpdateService/

这时候可以单独用命令运行程序,检测是否正常启动

sudo /home/administrator/dotnetFile/dotnet  /home/administrator/UpdateService/UpdateServer.dll

3.创建服务

创建服务文件:sudo vim /etc/systemd/system/update.service

然后将服务启动相关配置写入,里边的路径修改一下

[Unit]
Description=My .NET Service
After=network.target  # 网络就绪后启动[Service]
Type=notify           # 使用.NET的systemd通知机制
WorkingDirectory=/home/administrator/UpdateService/
ExecStart=sudo /home/administrator/dotnetFile/dotnet  /home/administrator/UpdateService/UpdateServer.dll
Restart=always        # 崩溃时自动重启
RestartSec=10[Install]
WantedBy=multi-user.target # 多用户模式启用

再赋予权限: sudo chmod 777 /etc/systemd/system/update.service

接着重载服务配置:sudo systemctl daemon-reload

下面就可以启动服务了:

sudo systemctl start update.service      # 立即启动
sudo systemctl enable update.service     # 启用开机自启
systemctl status update.service         # 检查运行状态
journalctl -u myapp -f          # 实时查看日志(调试必备)

4.测试连接

运行好之后,可以用TCP工具测试连接是否正常,收发数据是否正常:

验证完一切OK后,就可以尝试重启树莓派,看下是否开机启动正常

http://www.lryc.cn/news/575139.html

相关文章:

  • 使用 Spread.net将 Excel 中的文本拆分为多段
  • 数据文件写入技术详解:从CSV到Excel的ETL流程优化
  • BGP边界网关协议
  • 【基础篇-消息队列】——如何通过网络传输结构化的数据( 序列化与反序列化)
  • Class00.3矩阵计算
  • Linux进程控制与进程间通信(IPC)全面指南
  • Prompt:面向目标的提示词
  • Java如何导出word(根据模板生成),通过word转成pdf,放压缩包
  • aspose.word在IIS后端DLL中高并发运行,线程安全隔离
  • Java8 Stream流:Stream流的思想和获取Stream流
  • CTF Writeup: [强网杯 2019]随便注挑战解析
  • selenium UI自动化元素定位中classname和CSS区别
  • 渗透靶场:事件和属性被阻止的反射xss
  • Vue+ECharts后台仪表盘加载地图功能
  • Android14音频子系统-ASoC-ALSA之DAPM电源管理子系统
  • 个人技术文档库构建实践:基于Cursor和GitHub的知识管理系统(含cursor rules)
  • Github Copilot协助解决cucumber插件不支持async/await
  • 【Orange Pi Zero 3】-usb摄像头项目
  • 服务器性能优化通用方案
  • 一个项目中调用两个不同后台,前端如何优雅实现无感刷新Token调用接口
  • webpack5 css-loader:从基础到原理
  • css实现a标签前面加小图标
  • 【GStreamer】减小延时的参数设置、从RTP中获取时间戳
  • 深入探索WordPress Multisite:构建与管理多站点网络
  • 【Lua 基础学习】
  • C++(智能指针)
  • LeetCode 3298.统计重新排列后包含另一个字符串的子字符串数目2
  • ivx创建一个测试小案例
  • Vue3插槽
  • 基于springboot+vue的智慧农业专家远程指导系统