C# 56. Tcp Server

火影  论坛元老 | 2024-12-21 01:58:02 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1017|帖子 1017|积分 3051

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1. TCP Server类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace Xxxxx
  9. {
  10.     public class TcpServer
  11.     {
  12.         private TcpListener listener;
  13.         private bool isRunning = false;
  14.         private dataProcessdelegate dataProcessFunc;
  15.         public bool StartServer(string ip, int port, dataProcessdelegate dataProcessFunc1)
  16.         {
  17.             if(isRunning == false)
  18.             {
  19.                 dataProcessFunc = dataProcessFunc1;
  20.                 IPAddress ipAddress = IPAddress.Parse(ip);
  21.                 listener = new TcpListener(ipAddress, port);
  22.                 Start();
  23.             }
  24.             else
  25.             {
  26.                 Stop();
  27.             }
  28.             return isRunning;
  29.         }
  30.         public void Start()
  31.         {
  32.             isRunning = true;
  33.             listener.Start();
  34.             Console.WriteLine($"Server started and listening on port {listener.LocalEndpoint}");
  35.             Task.Run(() => AcceptClientsAsync());
  36.         }
  37.         public void Stop()
  38.         {
  39.             isRunning = false;
  40.             listener.Stop();
  41.             client.Close();
  42.             Console.WriteLine("Server stopped.");
  43.         }
  44.         private async Task AcceptClientsAsync()
  45.         {
  46.             while (isRunning)
  47.             {
  48.                 try
  49.                 {
  50.                     TcpClient client = await listener.AcceptTcpClientAsync();       //#1
  51.                     Console.WriteLine("Client connected.");
  52.                     HandleClientAsync(client);      //#2,前面没有awiat则不会停在HandleClientAsync而是跳到#1。加了awiat则等待HandleClientAsync执行完成
  53.                 }
  54.                 catch (ObjectDisposedException) when (!isRunning)
  55.                 {
  56.                     // Server is stopping, ignore this exception
  57.                 }
  58.                 catch (Exception ex)
  59.                 {
  60.                     Console.WriteLine($"Error accepting client: {ex.Message}");
  61.                 }
  62.             }
  63.         }
  64.         private async Task HandleClientAsync(TcpClient client)
  65.         {
  66.             NetworkStream stream = client.GetStream();
  67.             byte[] buffer = new byte[2048];
  68.             int bytesRead;
  69.             bool isRunningLocally = true; // 局部标志,用于控制循环
  70.             try
  71.             {
  72.                 while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0 && isRunningLocally)
  73.                 {
  74.                     //string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  75.                     string message = System.Text.Encoding.Default.GetString(buffer, 0, bytesRead);
  76.                     Console.WriteLine($"Received from client: {message}");
  77.                     dataProcessFunc(buffer, bytesRead);
  78.                     // 检查服务器是否仍在运行
  79.                     if (!isRunning)
  80.                     {
  81.                         isRunningLocally = false; // 设置标志以跳出循环
  82.                     }
  83.                 }
  84.             }
  85.             catch (Exception ex)
  86.             {
  87.                 Console.WriteLine($"Error handling client: {ex.Message}");
  88.             }
  89.             finally
  90.             {
  91.                 client.Close();
  92.                 Console.WriteLine("Client disconnected.");
  93.             }
  94.         }
  95.     }
  96. }
复制代码
2. 主类

  1. //定义一个数据处理的委托
  2. dataProcessdelegate dataProcessFunc;
  3. TcpServer tcpServer = new TcpServer();
  4. private void buttonOpenServer_Click(object sender, EventArgs e)
  5. {
  6.     if (serialPort1.IsOpen)
  7.     {
  8.         MessageBox.Show("请先关闭串口!");
  9.         return;
  10.     }
  11.     bool flag;
  12.     dataProcessFunc = new dataProcessdelegate(CmdParseInvoke);   
  13.     flag = tcpServer.StartServer(textBoxIP.Text.Trim(), Convert.ToInt32(this.textBoxPort.Text.Trim()),  dataProcessFunc);
  14.     if (flag == true)   //已连接
  15.     {
  16.         CommType = CommTypeEnum.TcpType;
  17.         buttonOpenServer.Text = "关闭服务";
  18.         buttonOpenServer.BackColor = Color.LightCoral;
  19.     }
  20.     else
  21.     {
  22.         CommType = CommTypeEnum.UnSelectType;
  23.         buttonOpenServer.Text = "打开服务";
  24.         buttonOpenServer.BackColor = Color.LimeGreen;
  25.     }
  26. }
  27. private void CmdParseInvoke(byte[] buf, int length)
  28. {
  29.     Invoke((EventHandler)(delegate
  30.     {
  31.         CmdParse(buf, length);
  32.     })
  33.     );
  34. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

火影

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表