using LinuxTcpApp.TcpServer; using System; using System.Net; namespace LinuxTcpApp { class Program { private static AsyncTcpServer tcpServer; static void Main(string[] args) { Console.WriteLine("程序开始运行"); IPAddress ipAddress; IPAddress.TryParse("0.0.0.0", out ipAddress); tcpServer = new AsyncTcpServer(ipAddress, 9888); tcpServer.ClientConnected += TcpServer_ClientConnected; tcpServer.ClientDisconnected += TcpServer_ClientDisconnected; tcpServer.PlaintextReceived += TcpServer_PlaintextReceived; tcpServer.Start(); while (true) { Thread.Sleep(1); } } private static void TcpServer_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<string> e) { Console.WriteLine(e.Datagram); tcpServer.SendAll(e.Datagram); } private static void TcpServer_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e) { Console.WriteLine("连接断开"+ e.TcpClient.Client.LocalEndPoint.ToString()); } private static void TcpServer_ClientConnected(object sender, TcpClientConnectedEventArgs e) { Console.WriteLine("连接成功"+ e.TcpClient.Client.LocalEndPoint.ToString()); } } }
需要源码的后台私聊
我这里手动发布至文件夹,然后压缩上传到服务器
安装命令如下:
sudo apt-get install dotnet-sdk-5.0
如果apt下载不了,请更新
wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb sudo dpkg -i packages-microsoft-prod.deb sudo apt-get update
连接服务器工具我用的是Git Bash,使用ssh命令,登录解压命令用rar x linux-x64 进入解压后的文件夹查看tcp使用情况,使用命令netstat -apt 由上图所知,没有9888这个端口的服务启动过。 之后用dotnet 命令运行LinuxTcpApp.dll,即可启动程序 可以用调试助手,进行通讯测试程序是否有问题
使用nohup命令,让程序在后台运行。完整命令如下,参数可以百度了解。 再次查看,tcp使用情况,如下图所示:
至此利用C# 语言跨平台Tcp服务器程序开发部署完毕,当有大型程序任务开发时,此方法不推荐使用,最好使用容器,保证程序的运行的稳定性。