当前位置: 首页 > news >正文

C#使用Socket实现TCP服务器端

1、TCP服务器实现代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace PtLib.TcpServer
{public delegate void TcpReceivedEventHandler(TcpStateEventArgs args);public class TcpServer{#region 变量//接收委托public event TcpReceivedEventHandler TcpReceived;//服务器IPprivate string _ip = "127.0.0.1";//服务器端口号private int _port = 8080;//当前SocketSocket currentSocket = null;//当前线程Thread currentThread = null;//Socket字典public Dictionary<string,Socket> dictSocket = new Dictionary<string,Socket>();//线程字典public Dictionary<string,Thread> dictThread = new Dictionary<string,Thread>();//运行标志public bool isRun =false;//public bool isClientChanged = false;#endregion/// <summary>/// 构造函数/// </summary>/// <param name="ip"></param>/// <param name="port"></param>public TcpServer(string ip,int port){_ip = ip;_port = port;}/// <summary>/// 打开/// </summary>public void Open(){currentSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);currentSocket.Bind(endPoint);currentSocket.Listen(10);isRun = true;currentThread = new Thread(WatchConnect);currentThread.IsBackground = true;currentThread.Start();}/// <summary>/// 连接处理/// </summary>private void WatchConnect(){while (isRun){Socket connectSocket=currentSocket.Accept();dictSocket.Add(connectSocket.RemoteEndPoint.ToString(), connectSocket);isClientChanged = true;ParameterizedThreadStart pts = new ParameterizedThreadStart(Receiver);Thread thread = new Thread(pts);thread.IsBackground = true;thread.Start(connectSocket);dictThread.Add(connectSocket.RemoteEndPoint.ToString(), thread);}}/// <summary>/// 接收处理/// </summary>/// <param name="socketClientPara"></param>private void Receiver(object socketClientPara){Socket receiveSocket = socketClientPara as Socket;while(true){byte[] buffer = new byte[1024 * 1024];int length = -1;try{length = receiveSocket.Receive(buffer);}catch(SocketException ex){dictSocket.Remove(receiveSocket.RemoteEndPoint.ToString());dictThread.Remove(receiveSocket.RemoteEndPoint.ToString());isClientChanged = true;Console.WriteLine(ex.Message);break;}catch(Exception ex){Console.WriteLine(ex.Message);break;}if (length > 0){byte[] b = new byte[length];Buffer.BlockCopy(buffer, 0, b, 0, length);TcpStateEventArgs args = new TcpStateEventArgs();args.ip = receiveSocket.RemoteEndPoint.ToString();args.buffer = b;TcpReceived?.Invoke(args);}}}/// <summary>/// 发送/// </summary>/// <param name="ip"></param>/// <param name="data"></param>public void Send(string ip, byte[] data){dictSocket[ip].Send(data);}/// <summary>/// 关闭/// </summary>public void Close(){isRun = false;Thread.Sleep(1000);dictSocket.Clear();dictThread.Clear();if (currentSocket != null){currentSocket.Close();currentSocket = null;}if (currentThread.IsAlive){currentThread.Abort();}currentThread = null;}}/// <summary>/// Tcp状态事件参数类/// </summary>public class TcpStateEventArgs : EventArgs{public string ip;public byte[] buffer = null;}
}

2、应用程序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace TcpServer
{public partial class Form1 : Form{PtLib.TcpServer.TcpServer tcpServer= null;Timer timer=new Timer();/// <summary>/// 构造函数/// </summary>public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){timer.Interval = 1000;timer.Tick += Timer_Tick;timer.Start();}private void Timer_Tick(object sender, EventArgs e){if (tcpServer!=null && tcpServer.isClientChanged){List<string> list = new List<string>();foreach(var item in tcpServer.dictSocket.Keys){list.Add(item);}this.Invoke(new Action(() =>{cbbClientIps.DataSource = list;cbbClientIps.SelectedIndex = 0;}));tcpServer.isClientChanged = false;}}/// <summary>/// TCP服务器端打开或关闭/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btServerSwitch_Click(object sender, EventArgs e){if(btServerSwitch.Text.Equals("打    开")){btServerSwitch.Text = "关    闭";string ip = tbServerIp.Text.Trim();int port = int.Parse(tbServerPort.Text.Trim());tcpServer = new PtLib.TcpServer.TcpServer(ip, port);tcpServer.Open();tcpServer.TcpReceived += TcpServer_TcpReceived;}else{btServerSwitch.Text = "打    开";tcpServer.TcpReceived -= TcpServer_TcpReceived;tcpServer.Close();}}private void TcpServer_TcpReceived(PtLib.TcpServer.TcpStateEventArgs args){string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")+":"+args.ip+",";str += Encoding.UTF8.GetString(args.buffer);this.Invoke(new Action(() =>{lbxReceive.Items.Add(str);}));}/// <summary>/// 数据发送/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnSend_Click(object sender, EventArgs e){string ip= cbbClientIps.SelectedItem.ToString();string str=tbSend.Text.Trim();byte[] sendBytes = Encoding.UTF8.GetBytes(str);tcpServer.Send(ip, sendBytes);}}
}

3、运行效果
在这里插入图片描述

相关文章:

C#使用Socket实现TCP服务器端

1、TCP服务器实现代码 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks;namespace PtLib.TcpServer {public delegate void Tcp…...

MTK联发科MT8766/MT8166安卓核心板性能参数对

MT8766核心板 采用联发科四核2G主频芯片方案&#xff0c;国内4G全网通。12nm先进工艺&#xff0c;支持 Android9.0系统。 GPU 采用超强 IMG GE8300 ,主频600MHz。支持高速LPDDR4/X&#xff0c;主频高达1600MHz。支持EMMC5.1。标配 WIFI 802.11 ac/abgn&#xff0c;BT 5.0。 支持…...

ps绘制动图

ps绘制动图教程&#xff08;简易版&#xff09;-直播gif动态效果图 第一步 打开ps绘制几个简单的长方形 第二步 将图层转化为智能图层 第三部 在窗口找到时间轴创建时间轴 第五步 通过变换来鼠标控制图像的变化并打下结束点 第六部 通过图像中的图像大小控制gif的大小 第七部 …...

AI学习指南机器学习篇-强化学习和深度学习简介

AI学习指南机器学习篇-强化学习和深度学习简介 强化学习和深度学习基本概念回顾 强化学习是一种机器学习方法&#xff0c;其目标是让智能体通过与环境的交互来学习最优的行为策略。在强化学习中&#xff0c;智能体不需要标记的训练数据&#xff0c;而是通过试错来提升自己的表…...

yolov8 bytetrack onnx模型推理

原文&#xff1a;yolov8 bytetrack onnx模型推理 - 知乎 (zhihu.com) 一、pt模型转onnx from ultralytics import YOLO# Load a model model YOLO(weights/yolov8s.pt) # load an official model # model YOLO(path/to/best.pt) # load a custom trained# Export the mod…...

ImageNet数据集和CIFAR-10数据集

一、为什么需要大量数据集 人工智能其实就是大数据的时代&#xff0c;无论是目标检测、图像分类、还是现在植入我们生活的推荐系统&#xff0c;“喂入”神经网络的数据越多&#xff0c;则识别效果越好、分类越准确。因此开源大型数据集的研究团队为人工智能的发展做了大量贡献…...

Go语言编程大全,web微服务数据库十大专题精讲

本课程主要从数据结构、Go Module 依赖管理、IO编程、数据库编程、消息队列、加密技术与网络安全、爬虫与反爬虫、web开发、微服务通用技术、Kitex框架等方面讲解~ 链接&#xff1a;https://pan.quark.cn/s/d65337a0e60d...

【LabVIEW学习篇 - 13】:队列

文章目录 队列 队列 队列通常情况下是一种先入先出&#xff08;FIFO&#xff1a;First in First out&#xff09;的数据结构&#xff0c;常用作数据缓存&#xff0c;通过队列结构可以保证数据有序的传递&#xff0c;避免竞争和冲突。 案例&#xff1a;利用队列&#xff0c;模…...

大语言模型综述泛读之Large Language Models: A Survey

摘要 这篇文章主要回顾了一些最突出的LLMs(GPT, LLaMA, PaLM)并讨论了它们的特点、贡献和局限性,就如何构建增强LLMs做了一个技术概述,然后调研了为LLM训练、微调和评估而准备的N多种流行数据集,审查了使用的LLM评价指标,在一组有代表性的基准上比较了几个流行的LLMs;最…...

奇偶函数的性质及运算

目录 定义 注意 特征 运算 拓展 定义 设函数f(x)的定义域D&#xff1b; 如果对于函数定义域D内的任意一个x&#xff0c;都有f(-x)&#xff0d;f&#xff08;x&#xff09;&#xff0c;那么函数f&#xff08;x&#xff09;就叫做奇函数。如果对于函数定义域D内的任意一个x…...

代码随想录 day 32 动态规划

第九章 动态规划part01 今天正式开始动态规划&#xff01; 理论基础 无论大家之前对动态规划学到什么程度&#xff0c;一定要先看 我讲的 动态规划理论基础。 如果没做过动态规划的题目&#xff0c;看我讲的理论基础&#xff0c;会有感觉 是不是简单题想复杂了&#xff1f; …...

支持目标检测的框架有哪些

目标检测是计算机视觉领域的一个重要任务&#xff0c;许多深度学习框架都提供了对目标检测的支持。以下是一些广泛使用的支持目标检测的深度学习框架&#xff1a; 1. TensorFlow TensorFlow 是一个广泛使用的开源深度学习框架&#xff0c;由Google开发。它提供了TensorFlow O…...

原神自定义倒计时

<!DOCTYPE html> <html lang"zh-CN"><head><meta charset"UTF-8"><title>原神倒计时</title><style>* {margin: 0;padding: 0;box-sizing: border-box;user-select: none;body {background: #0b1b2c;}}header {…...

top命令实时监测Linux进程

top命令可以动态实时显示Linux进程信息&#xff0c;方便观察频繁换进换出的内存的进程变化。 top命令执行示例如下&#xff1a; 其中&#xff0c;第一行表示系统当前时间、系统的运行时间、登录的用户数目、系统的平均负载&#xff08;最近1分钟&#xff0c;最近5分钟&#xff…...

Rust 所有权

所有权 Rust的核心特性就是所有权所有程序在运行时都必须管理他们使用计算机内存的方式 有些语言有垃圾收集机制&#xff0c;在程序运行时&#xff0c;他们会不断地寻找不再使用的内存在其他语言中&#xff0c;程序员必须显式的分配和释放内存 Rust采用了第三种方式&#xff1…...

Python面试题:结合Python技术,如何使用PyTorch进行动态计算图构建

PyTorch 是一个流行的深度学习框架&#xff0c;它通过动态计算图&#xff08;Dynamic Computation Graphs&#xff09;来支持自动微分&#xff08;Autograd&#xff09;。动态计算图的特点是每次前向传播时都会构建新的计算图&#xff0c;这使得它非常灵活&#xff0c;适合处理…...

基于RHEL7的服务器批量安装

目录 一、项目要求 二、实验环境 三、生成kickstart自动化安装脚本 四、搭建dhcp服务并测试kickstart脚本 五、搭建pxe网络安装环境实现服务器自动部署 ​编辑 六、测试 一、项目要求 1.使用kickstart编写自动化安装脚本 2.搭建dhcp服务并测试kickstart脚本 3.搭建px…...

C. Light Switches

文章目录 C. Light Switches题意&#xff1a;解题思路&#xff1a;解题代码&#xff1a; C. Light Switches 原题链接 题意&#xff1a; 房间的灯最初均为关闭状态&#xff0c;安装芯片后&#xff0c;它会每隔k分钟改变一次房间的灯光状态&#xff0c;即会打开灯光k分钟&…...

LabVIEW机器人神经网络运动控制系统

LabVIEW机器人神经网络运动控制系统 介绍了如何使用LabVIEW软件和中枢模式发生器(CPG)神经网络实现对舵机驱动爬壁机器人的精准运动控制。通过结合仿生控制理念与高级程序设计&#xff0c;本项目旨在开发一种能自动完成复杂墙面移动任务的机器人。 项目背景 现代机器人技术中…...

Qt WebEngine播放DRM音视频

Qt WebEngine播放DRM受保护视频&#xff0c;前提是Qt WebEngine开启音视频编码器&#xff0c;能够支持网页上普通视频的播放。开启音视频编码器需要自己编译源码&#xff0c;这里不做介绍。 什么是DRM音视频 DRM视频是指数字版权管理&#xff08;Digital Rights Management&a…...

智慧医疗能源事业线深度画像分析(上)

引言 医疗行业作为现代社会的关键基础设施,其能源消耗与环境影响正日益受到关注。随着全球"双碳"目标的推进和可持续发展理念的深入,智慧医疗能源事业线应运而生,致力于通过创新技术与管理方案,重构医疗领域的能源使用模式。这一事业线融合了能源管理、可持续发…...

突破不可导策略的训练难题:零阶优化与强化学习的深度嵌合

强化学习&#xff08;Reinforcement Learning, RL&#xff09;是工业领域智能控制的重要方法。它的基本原理是将最优控制问题建模为马尔可夫决策过程&#xff0c;然后使用强化学习的Actor-Critic机制&#xff08;中文译作“知行互动”机制&#xff09;&#xff0c;逐步迭代求解…...

ssc377d修改flash分区大小

1、flash的分区默认分配16M、 / # df -h Filesystem Size Used Available Use% Mounted on /dev/root 1.9M 1.9M 0 100% / /dev/mtdblock4 3.0M...

PL0语法,分析器实现!

简介 PL/0 是一种简单的编程语言,通常用于教学编译原理。它的语法结构清晰,功能包括常量定义、变量声明、过程(子程序)定义以及基本的控制结构(如条件语句和循环语句)。 PL/0 语法规范 PL/0 是一种教学用的小型编程语言,由 Niklaus Wirth 设计,用于展示编译原理的核…...

涂鸦T5AI手搓语音、emoji、otto机器人从入门到实战

“&#x1f916;手搓TuyaAI语音指令 &#x1f60d;秒变表情包大师&#xff0c;让萌系Otto机器人&#x1f525;玩出智能新花样&#xff01;开整&#xff01;” &#x1f916; Otto机器人 → 直接点明主体 手搓TuyaAI语音 → 强调 自主编程/自定义 语音控制&#xff08;TuyaAI…...

RSS 2025|从说明书学习复杂机器人操作任务:NUS邵林团队提出全新机器人装配技能学习框架Manual2Skill

视觉语言模型&#xff08;Vision-Language Models, VLMs&#xff09;&#xff0c;为真实环境中的机器人操作任务提供了极具潜力的解决方案。 尽管 VLMs 取得了显著进展&#xff0c;机器人仍难以胜任复杂的长时程任务&#xff08;如家具装配&#xff09;&#xff0c;主要受限于人…...

uniapp 字符包含的相关方法

在uniapp中&#xff0c;如果你想检查一个字符串是否包含另一个子字符串&#xff0c;你可以使用JavaScript中的includes()方法或者indexOf()方法。这两种方法都可以达到目的&#xff0c;但它们在处理方式和返回值上有所不同。 使用includes()方法 includes()方法用于判断一个字…...

Golang——7、包与接口详解

包与接口详解 1、Golang包详解1.1、Golang中包的定义和介绍1.2、Golang包管理工具go mod1.3、Golang中自定义包1.4、Golang中使用第三包1.5、init函数 2、接口详解2.1、接口的定义2.2、空接口2.3、类型断言2.4、结构体值接收者和指针接收者实现接口的区别2.5、一个结构体实现多…...

xmind转换为markdown

文章目录 解锁思维导图新姿势&#xff1a;将XMind转为结构化Markdown 一、认识Xmind结构二、核心转换流程详解1.解压XMind文件&#xff08;ZIP处理&#xff09;2.解析JSON数据结构3&#xff1a;递归转换树形结构4&#xff1a;Markdown层级生成逻辑 三、完整代码 解锁思维导图新…...

Matlab实现任意伪彩色图像可视化显示

Matlab实现任意伪彩色图像可视化显示 1、灰度原始图像2、RGB彩色原始图像 在科研研究中&#xff0c;如何展示好看的实验结果图像非常重要&#xff01;&#xff01;&#xff01; 1、灰度原始图像 灰度图像每个像素点只有一个数值&#xff0c;代表该点的​​亮度&#xff08;或…...