wpf mvvm框架下创建一个TCP 服务端

55 篇文章 6 订阅

在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执行命令。

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白话Learning

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值