C# Tcplistener,Tcp服务端简易封装

2023-12-19 12:20

本文主要是介绍C# Tcplistener,Tcp服务端简易封装,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 前言
  • 相关文章
  • 前言
  • 设计
  • 代码
  • 简单使用
  • 运行结果

前言

我最近有个需求要写Tcp服务端,我发现Tcp服务端的回调函数比较麻烦,简化Tcp的服务,我打算自己封装一个简单的Tcp服务端。

相关文章

C# TCP应用编程三 异步TCP应用编程

C# Tcpclient Tcplistener 服务器接收多个客户端消息通讯

关于C#Socket断开重连问题

前言

我最近有个Tcp服务端的项目,发现TcpListener 服务端官方写起来很麻烦。而且没有回调函数。现在做个简单的服务端封装

设计

TcpServerService
ShowMsg:打印消息
AddClient_CallBack:新增Tcp客户端回调函数
SendMsg/ReceiveMsg:Tcp客户端发送接受回调
Clients:Tcp客户端集合,连接增加,断开去除
其它函数

代码

 public class TcpServeService{public string Ip { get; set; }public int Port { get; set; }public TcpListener Server { get; set; }public List<TcpClient> Clients { get; set; }/// <summary>/// 客户端添加回调函数,如果要重写通讯逻辑需要覆盖/// </summary>public Action<TcpClient> AddClient_CallBack { get; set; }public Action<string> ShowMsg { get; set; }/// <summary>/// 默认自动回复Tcp服务端/// </summary>/// <param name="ip"></param>/// <param name="port"></param>public TcpServeService(string ip, int port){Clients = new List<TcpClient>();ShowMsg = (msg) => Console.WriteLine(msg);AddClient_CallBack = (client) => AutoSendBack(client);this.Ip = ip;this.Port = port;Server = new TcpListener(IPAddress.Parse(ip), port);}/// <summary>/// Tcp添加Client回调/// </summary>/// <param name="ar"></param>private void DoAcceptTcpclient(IAsyncResult ar){// Get the listener that handles the client request.TcpListener listener = (TcpListener)ar.AsyncState;// End the operation and display the received data on // the console.TcpClient client = listener.EndAcceptTcpClient(ar);Clients.Add(client);// Process the connection here. (Add the client to a// server table, read data, etc.)ShowMsg($"Tcp客户端连接成功!,当前连接数{Clients.Count},Id[{client.Client.RemoteEndPoint.ToString()}]");AddClient_CallBack(client);//开启线程用来不断接收来自客户端的数据Server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), Server);}/// <summary>/// 移除Tcp客户端/// </summary>/// <param name="client"></param>public void RemoveClient(TcpClient client){NetworkStream stream = client.GetStream();ShowMsg($"Tcp客户端连接断开!,当前连接数{Clients.Count},Id[{client.Client.RemoteEndPoint.ToString()}]");stream.Close();client.Close();Clients.Remove(client);}/// <summary>/// 启动Tcp服务/// </summary>public void Start(){Server.Start();Server.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpclient), Server);ShowMsg($"Tcp服务端启动成功!IP[{Ip}],Port[{Port}]");}/// <summary>/// 同步阻塞读取数据/// </summary>/// <param name="client"></param>/// <returns></returns>public static (string str, byte[] bytes) ReadMsg(TcpClient client){NetworkStream networkStream = client.GetStream();var resBytes = new byte[client.ReceiveBufferSize];networkStream.Read(resBytes, 0, resBytes.Length);var resStr = UnicodeEncoding.ASCII.GetString(resBytes);if (!IsConnect(client)){throw new Exception($"{client.Client.RemoteEndPoint?.ToString()}Tcp连接已断开");}return (resStr, resBytes);}/// <summary>/// 发送Ascll数据/// </summary>/// <param name="tcpClient"></param>/// <param name="msg"></param>public static void SendMsg(TcpClient tcpClient, string msg){byte[] arrSendMsg = Encoding.UTF8.GetBytes(msg);SendMsg(tcpClient, arrSendMsg);}/// <summary>/// Tcp客户端连接是否断开/// </summary>/// <param name="tcpClient"></param>/// <returns></returns>public static bool IsConnect(TcpClient tcpClient){if (tcpClient.Client.Poll(1, SelectMode.SelectRead) && tcpClient.Available == 0){return false;}else { return true; }}/// <summary>/// 发送Bytes[]数据/// </summary>/// <param name="tcpClient"></param>/// <param name="msg"></param>public static void SendMsg(TcpClient tcpClient, byte[] msg){NetworkStream networkStream = tcpClient.GetStream();networkStream.Write(msg, 0, msg.Length);}/// <summary>/// 默认自动回复,异常捕捉/// </summary>/// <param name="tcpClient"></param>/// <param name="timeOut">超时时间</param>/// <returns></returns>public async Task AutoSendBack(TcpClient tcpClient, int timeOut = 10 * 1000){//超时时间tcpClient.ReceiveTimeout = timeOut;tcpClient.SendTimeout = timeOut;while (true){try{if (!Clients.Contains(tcpClient)){throw new Exception("Tcp客户端已被移除!");}var receive = ReadMsg(tcpClient);ShowMsg($"TcpClient[{tcpClient.Client.RemoteEndPoint?.ToString()}]:收到数据{receive.str}");SendMsg(tcpClient, receive.str);}catch (Exception ex){RemoveClient(tcpClient);ShowMsg("发送失败");ShowMsg(ex.Message);}}}

简单使用

//对tcpServeService进行了默认配置,默认自动回复,自动维护Client集合
TcpServeService tcpServeService = new TcpServeService("192.168.100.21", 10003);//如果想要自定义回复,需要覆盖AddClient_CallBack函数,使用异步任务处理连接
//tcpServeService.AddClient_CallBack = ((client) => {
//    Task.Run(() =>
//    {
//        //你的客户端连接异步任务
//    });
//});//如果想要打印在Winfrom/WPF的界面,覆盖此回调
//tcpServeService.ShowMsg = (msg) =>
//{
//    //你的消息打印函数
//};
//tcpServeService.Start();
tcpServeService.Start();

运行结果

在这里插入图片描述

这篇关于C# Tcplistener,Tcp服务端简易封装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/512130

相关文章

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当

详解C#如何提取PDF文档中的图片

《详解C#如何提取PDF文档中的图片》提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使用,下面我们就来看看如何使用C#通过代码从PDF文档中提取图片吧... 当 PDF 文件中包含有价值的图片,如艺术画作、设计素材、报告图表等,提取图片可以将这些图像资源进行单独保存,方便后续在不同的项目中使

C#使用SQLite进行大数据量高效处理的代码示例

《C#使用SQLite进行大数据量高效处理的代码示例》在软件开发中,高效处理大数据量是一个常见且具有挑战性的任务,SQLite因其零配置、嵌入式、跨平台的特性,成为许多开发者的首选数据库,本文将深入探... 目录前言准备工作数据实体核心技术批量插入:从乌龟到猎豹的蜕变分页查询:加载百万数据异步处理:拒绝界面

C#数据结构之字符串(string)详解

《C#数据结构之字符串(string)详解》:本文主要介绍C#数据结构之字符串(string),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录转义字符序列字符串的创建字符串的声明null字符串与空字符串重复单字符字符串的构造字符串的属性和常用方法属性常用方法总结摘

C#如何动态创建Label,及动态label事件

《C#如何动态创建Label,及动态label事件》:本文主要介绍C#如何动态创建Label,及动态label事件,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#如何动态创建Label,及动态label事件第一点:switch中的生成我们的label事件接着,

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

SpringBoot中封装Cors自动配置方式

《SpringBoot中封装Cors自动配置方式》:本文主要介绍SpringBoot中封装Cors自动配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录SpringBoot封装Cors自动配置背景实现步骤1. 创建 GlobalCorsProperties

C#基础之委托详解(Delegate)

《C#基础之委托详解(Delegate)》:本文主要介绍C#基础之委托(Delegate),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 委托定义2. 委托实例化3. 多播委托(Multicast Delegates)4. 委托的用途事件处理回调函数LINQ

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

C#中的 StreamReader/StreamWriter 使用示例详解

《C#中的StreamReader/StreamWriter使用示例详解》在C#开发中,StreamReader和StreamWriter是处理文本文件的核心类,属于System.IO命名空间,本... 目录前言一、什么是 StreamReader 和 StreamWriter?1. 定义2. 特点3. 用