在C#项目中,可以使用TcpClient类来创建一个TCP服务端,实时监听连接的客户端并接收字符串数据。在wpf mvvm框架下,我们创建一个ViewModel,在项目中添加类:
在类中添加如下代码:
using DataHelper;using Newtonsoft.Json;using QZ.General;using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.ComponentModel;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;using Utility.Log;namespace LSRRejudication.ViewModels{public class TPCServerViewModel : BaseNotify{private bool RunFlag = true;private int _port = 8887;[Description("端口")]public int port{get { return _port; }set { SetProperty(ref _port, value); }}private bool _serverIsConnected = false;[Description("server是否是连接状态")][JsonIgnore]public bool serverIsConnected{get { return _serverIsConnected; }set { SetProperty(ref _serverIsConnected, value); }}private List<EndPoint> _connetedCliantsEanPoints =new List<EndPoint>();[Description("")][JsonIgnore]public ObservableCollection<EndPoint> ConnetedCliantsEanPoints{get { return _connetedCliantsEanPoints; }set { SetProperty(ref _connetedCliantsEanPoints, value); }}[JsonIgnore]List<TcpClient> clients = new List<TcpClient>();public async Task ServerInitAsync(){try{// 创建 TcpListener 对象并开始监听端口TcpListener listener = new TcpListener(IPAddress.Any, port);listener.Start();while (RunFlag){//接受客户端连接请求并创建对应的 TcpClient 对象TcpClient client = await listener.AcceptTcpClientAsync();//Console.WriteLine($"Client connected: {client.Client.RemoteEndPoint}");ConnetedCliantsEanPoints.Add(client.Client.RemoteEndPoint);serverIsConnected = client.Connected;clients.Add(client);//若要接收数据可以开发一个线程实时接收数据}}catch (Exception ex){ConnetedCliantsEanPoints.Clear();logMangerError.ConsoleMessage("TPC服务端初始化" + ex.Message);}}public bool SendToAll(string sendMsg){try{byte[] buffer = Encoding.UTF8.GetBytes(sendMsg);List<TcpClient> disconnectedClients = new List<TcpClient>();// 遍历客户端列表,向所有连接的客户端发送数据lock (clients){foreach (TcpClient client in clients){try{if (client.Connected){NetworkStream stream = client.GetStream();stream.WriteAsync(buffer, 0, buffer.Length);}}catch (Exception){// 如果发送失败,说明客户端已经断开连接,将其加入到断开连接的客户端列表中disconnectedClients.Add(client); }}// 从客户端列表中移除已经断开连接的客户端foreach (TcpClient client in disconnectedClients){clients.Remove(client);ConnetedCliantsEanPoints.Remove(client.Client.RemoteEndPoint);}}}catch (Exception ex){console.WriteLine("TCPSercver 发送数据异常:" + ex.Message);return false;}return true;}//断开连接public void DisConneted(){try{foreach (TcpClient client in clients){client" />Close();client?.Dispose();}RunFlag = false;ConnetedCliantsEanPoints.Clear();}catch (Exception ex){console.WriteLine("Server 断开连接异常" + ex.Message);}}}}
给服务实现了启动监听所有连接的客户端,并可以发送数据到连接的所有客户端,当客户端断线时,在监听列表中移除。
当然这只是实现服务端初始化的过程,在mvvm框架中,还需要引用响应的头文件,如继承BaseNotify需引用响应的头文件(vs2022鼠标移动到报错位置,在提示栏中 【显示的可能修补程序】选择即可)。
mvvm框架下当前端需要调用时,也可将服务端初始化、断开连接等封装成command执行命令。