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

C#网络连接:TCP/IP模式下的网络连接与同步

1,目的

为了测试局域网的消息同步,简单写了下TCP/IP模式的同步,参考这个帖子。

2,核心库部分

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;namespace Coldairarrow.Util.Sockets
{/// <summary>/// Socket客户端/// </summary>public class SocketClient{#region 构造函数/// <summary>/// 构造函数,连接服务器IP地址默认为本机127.0.0.1/// </summary>/// <param name="port">监听的端口</param>public SocketClient(int port){_ip = "127.0.0.1";_port = port;}/// <summary>/// 构造函数/// </summary>/// <param name="ip">监听的IP地址</param>/// <param name="port">监听的端口</param>public SocketClient(string ip, int port){_ip = ip;_port = port;}#endregion#region 内部成员private Socket _socket = null;private string _ip = "";private int _port = 0;private bool _isRec=true;private bool IsSocketConnected(){bool part1 = _socket.Poll(1000, SelectMode.SelectRead);bool part2 = (_socket.Available == 0);if (part1 && part2)return false;elsereturn true;}/// <summary>/// 开始接受客户端消息/// </summary>public void StartRecMsg(){try{byte[] container = new byte[1024 * 1024 * 2];_socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndReceive(asyncResult);//马上进行下一轮接受,增加吞吐量if (length > 0 && _isRec && IsSocketConnected())StartRecMsg();if (length > 0){byte[] recBytes = new byte[length];Array.Copy(container, 0, recBytes, 0, length);//处理消息HandleRecMsg?.Invoke(recBytes, this);}elseClose();}catch (Exception ex){HandleException?.Invoke(ex);Close();}}, null);}catch (Exception ex){HandleException?.Invoke(ex);Close();}}#endregion#region 外部接口/// <summary>/// 开始服务,连接服务端/// </summary>public void StartClient(){try{//实例化 套接字 (ip4寻址协议,流式传输,TCP协议)_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建 ip对象IPAddress address = IPAddress.Parse(_ip);//创建网络节点对象 包含 ip和portIPEndPoint endpoint = new IPEndPoint(address, _port);//将 监听套接字  绑定到 对应的IP和端口_socket.BeginConnect(endpoint, asyncResult =>{try{_socket.EndConnect(asyncResult);//开始接受服务器消息StartRecMsg();HandleClientStarted?.Invoke(this);}catch (Exception ex){HandleException?.Invoke(ex);}}, null);}catch (Exception ex){HandleException?.Invoke(ex);}}/// <summary>/// 发送数据/// </summary>/// <param name="bytes">数据字节</param>public void Send(byte[] bytes){try{_socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndSend(asyncResult);HandleSendMsg?.Invoke(bytes, this);}catch (Exception ex){HandleException?.Invoke(ex);}}, null);}catch (Exception ex){HandleException?.Invoke(ex);}}/// <summary>/// 发送字符串(默认使用UTF-8编码)/// </summary>/// <param name="msgStr">字符串</param>public void Send(string msgStr){Send(Encoding.UTF8.GetBytes(msgStr));}/// <summary>/// 发送字符串(使用自定义编码)/// </summary>/// <param name="msgStr">字符串消息</param>/// <param name="encoding">使用的编码</param>public void Send(string msgStr, Encoding encoding){Send(encoding.GetBytes(msgStr));}/// <summary>/// 传入自定义属性/// </summary>public object Property { get; set; }/// <summary>/// 关闭与服务器的连接/// </summary>public void Close(){try{_isRec = false;_socket.Disconnect(false);HandleClientClose?.Invoke(this);}catch (Exception ex){HandleException?.Invoke(ex);}}#endregion#region 事件处理/// <summary>/// 客户端连接建立后回调/// </summary>public Action<SocketClient> HandleClientStarted { get; set; }/// <summary>/// 处理接受消息的委托/// </summary>public Action<byte[], SocketClient> HandleRecMsg { get; set; }/// <summary>/// 客户端连接发送消息后回调/// </summary>public Action<byte[], SocketClient> HandleSendMsg { get; set; }/// <summary>/// 客户端连接关闭后回调/// </summary>public Action<SocketClient> HandleClientClose { get; set; }/// <summary>/// 异常处理程序/// </summary>public Action<Exception> HandleException { get; set; }#endregion}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace Coldairarrow.Util.Sockets
{/// <summary>/// Socket连接,双向通信/// </summary>public class SocketConnection{#region 构造函数public SocketConnection(Socket socket, SocketServer server){_socket = socket;_server = server;}#endregion#region 私有成员private readonly Socket _socket;private bool _isRec = true;private SocketServer _server = null;private bool IsSocketConnected(){bool part1 = _socket.Poll(1000, SelectMode.SelectRead);bool part2 = (_socket.Available == 0);if (part1 && part2)return false;elsereturn true;}#endregion#region 外部接口/// <summary>/// 开始接受客户端消息/// </summary>public void StartRecMsg(){try{byte[] container = new byte[1024 * 1024 * 6];_socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndReceive(asyncResult);///asyncResult.AsyncWaitHandle.Close();//马上进行下一轮接受,增加吞吐量if (length > 0 && _isRec && IsSocketConnected())StartRecMsg();if (length > 0){byte[] recBytes = new byte[length];Array.Copy(container, 0, recBytes, 0, length);string msgJson = Encoding.UTF8.GetString(recBytes);if (msgJson.Contains("¤€") && msgJson.Contains("€¤")){string[] arrymsg = msgJson.Replace("¤€", "卍").Split('卍');foreach (string msgitem in arrymsg){if (string.IsNullOrEmpty(msgitem))continue;if (msgitem.Substring(msgitem.Length - 2, 2) == "€¤"){string msgitemjson = msgitem.Substring(0, msgitem.Length - 2);//处理消息HandleRecMsg?.Invoke(msgitemjson, this, _server);}}}else{HandleException?.Invoke(new Exception($"接收到错误指令,具体指令为:{msgJson}"));}}elseClose();}catch (Exception ex){HandleException?.Invoke(ex);Close();}}, null);}catch (Exception ex){HandleException?.Invoke(ex);Close();}}/// <summary>/// 发送数据/// </summary>/// <param name="bytes">数据字节</param>private void Send(byte[] bytes){try{_socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndSend(asyncResult);HandleSendMsg?.Invoke(bytes, this, _server);UnityEngine.Debug.Log("发送成功");}catch (Exception ex){                        HandleSendException?.Invoke(ex);UnityEngine.Debug.Log("发送"+ex);}}, null);}catch (Exception ex){HandleSendException?.Invoke(ex);}}/// <summary>/// 发送字符串(默认使用UTF-8编码)/// </summary>/// <param name="msgStr">字符串</param>public void Send(string msgStr){Send(Encoding.UTF8.GetBytes("¤€" + msgStr + "€¤"));}/// <summary>/// 发送字符串(使用自定义编码)/// </summary>/// <param name="msgStr">字符串消息</param>/// <param name="encoding">使用的编码</param>public void Send(string msgStr, Encoding encoding){Send(encoding.GetBytes("¤€" + msgStr + "€¤"));}/// <summary>/// 传入自定义属性/// </summary>public object Property { get; set; }/// <summary>/// 关闭当前连接/// </summary>public void Close(){try{_isRec = false;_socket.Disconnect(false);_server.ClientList.Remove(this);HandleClientClose?.Invoke(this, _server);_socket.Close();_socket.Dispose();GC.Collect();}catch (Exception ex){HandleException?.Invoke(ex);}}#endregion#region 事件处理/// <summary>/// 客户端连接接受新的消息后调用/// </summary>public Action<string, SocketConnection, SocketServer> HandleRecMsg { get; set; }/// <summary>/// 客户端连接发送消息后回调/// </summary>public Action<byte[], SocketConnection, SocketServer> HandleSendMsg { get; set; }/// <summary>/// 客户端连接关闭后回调/// </summary>public Action<SocketConnection, SocketServer> HandleClientClose { get; set; }/// <summary>/// 异常处理程序/// </summary>public Action<Exception> HandleException { get; set; }/// <summary>/// 发送消息到客户端异常/// </summary>public Action<Exception> HandleSendException { get; set; }#endregion}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace Coldairarrow.Util.Sockets
{/// <summary>/// Socket服务端/// </summary>public class SocketServer{private static string ipAddressStr = "127.0.0.1";//IP地址字符串private static int port = 5500;//端口#region 内部成员private Socket _socket = null;private bool _isListen = true;public static ManualResetEvent allDone = new ManualResetEvent(false);private void StartListen(){try{_socket.BeginAccept(asyncResult =>{try{Socket newSocket = _socket.EndAccept(asyncResult);//马上进行下一轮监听,增加吞吐量if (_isListen)StartListen();SocketConnection newClient = new SocketConnection(newSocket, this){HandleRecMsg = HandleRecMsg == null ? null : new Action<string, SocketConnection, SocketServer>(HandleRecMsg),HandleClientClose = HandleClientClose == null ? null : new Action<SocketConnection, SocketServer>(HandleClientClose),HandleSendMsg = HandleSendMsg == null ? null : new Action<byte[], SocketConnection, SocketServer>(HandleSendMsg),HandleException = HandleException == null ? null : new Action<Exception>(HandleException),HandleSendException = HandleSendException == null ? null : new Action<Exception>(HandleSendException)};newClient.StartRecMsg();ClientList.AddLast(newClient);HandleNewClientConnected?.Invoke(this, newClient);}catch (Exception ex){//UnityEngine.Debug.LogError(ex);HandleException?.Invoke(ex);}}, null);}catch (Exception ex){//UnityEngine.Debug.LogError(ex);HandleException?.Invoke(ex);}}#endregion#region 外部接口/// <summary>/// 开始服务,监听客户端/// </summary>public void StartServer(){try{//实例化套接字(ip4寻址协议,流式传输,TCP协议)_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建ip对象IPAddress address = IPAddress.Parse(ipAddressStr);//创建网络节点对象包含ip和portIPEndPoint endpoint = new IPEndPoint(address, port);//将 监听套接字绑定到 对应的IP和端口_socket.Bind(endpoint);//设置监听队列长度为Int32最大值(同时能够处理连接请求数量)_socket.Listen(int.MaxValue);//开始监听客户端StartListen();HandleServerStarted?.Invoke(this);}catch (Exception ex){StartException?.Invoke(ex);}}/// <summary>/// 所有连接的客户端列表/// </summary>public LinkedList<SocketConnection> ClientList { get; set; } = new LinkedList<SocketConnection>();/// <summary>/// 关闭指定客户端连接/// </summary>/// <param name="theClient">指定的客户端连接</param>public void CloseClient(SocketConnection theClient){theClient.Close();}#endregion#region 公共事件/// <summary>/// 异常处理程序/// </summary>public Action<Exception> HandleException { get; set; }/// <summary>/// 发送消息异常处理程序/// </summary>public Action<Exception> HandleSendException { get; set; }/// <summary>/// 启动异常程序/// </summary>public Action<Exception> StartException { get; set; }#endregion#region 服务端事件/// <summary>/// 服务启动后执行/// </summary>public Action<SocketServer> HandleServerStarted { get; set; }/// <summary>/// 当新客户端连接后执行/// </summary>public Action<SocketServer, SocketConnection> HandleNewClientConnected { get; set; }/// <summary>/// 服务端关闭客户端后执行/// </summary>public Action<SocketServer, SocketConnection> HandleCloseClient { get; set; }#endregion#region 客户端连接事件/// <summary>/// 客户端连接接受新的消息后调用/// </summary>public Action<string, SocketConnection, SocketServer> HandleRecMsg { get; set; }/// <summary>/// 客户端连接发送消息后回调/// </summary>public Action<byte[], SocketConnection, SocketServer> HandleSendMsg { get; set; }/// <summary>/// 客户端连接关闭后回调/// </summary>public Action<SocketConnection, SocketServer> HandleClientClose { get; set; }#endregion}
}

3,服务器测试部分

using Coldairarrow.Util.Sockets;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class MySever : MonoBehaviour
{private System.Object obj=new System.Object();private class ParamEntity{public string ParamFace;public SocketConnection socketClient;}private List<ParamEntity> paramList=new List<ParamEntity> ();private bool IsRun = false;SocketServer server;void Start(){//创建服务器对象,默认监听本机0.0.0.0,端口12345server = new SocketServer();//处理从客户端收到的消息server.HandleRecMsg = new Action<string, SocketConnection, SocketServer>((msg, client, theServer) =>{Debug.Log($"调用次数");lock (obj){paramList.Add(new ParamEntity() { ParamFace = msg, socketClient = client });if (IsRun == false){IsRun = true;HandleMsg();}}});//处理服务器启动后事件server.HandleServerStarted = new Action<SocketServer>(theServer =>{Debug.Log("服务已启动************");});//处理新的客户端连接后的事件server.HandleNewClientConnected = new Action<SocketServer, SocketConnection>((theServer, theCon) =>{Debug.Log($@"一个新的客户端接入,当前连接数:{theServer.ClientList.Count}");});//处理客户端连接关闭后的事件server.HandleClientClose = new Action<SocketConnection, SocketServer>((theCon, theServer) =>{Debug.Log($@"一个客户端关闭,当前连接数为:{theServer.ClientList.Count}");});//处理异常server.HandleException = new Action<Exception>(ex =>{Debug.Log("Socket处理异常:" + ex.Message);});//处理异常server.HandleSendException = new Action<Exception>(ex =>{Debug.Log("Socket发送消息处理异常:" + ex.Message);});///启动异常server.StartException = new Action<Exception>(ex =>{Debug.Log("Socket服务启动失败:" + ex.Message);});//服务器启动server.StartServer();Debug.Log("启动Socket通信服务端完成。");}void HandleMsg(){Debug.LogError("HandleMsg");var _p = paramList[0];Debug.Log(_p.ParamFace);//方法1:返回给所有人(可以做挑选)var _list= server.ClientList;foreach (var _item in _list){_item.Send("收到转发:" + _p.ParamFace);}//方法2:仅返回给对应用户//_p.socketClient.Send(_p.ParamFace);paramList.Clear();IsRun = false;}// Update is called once per framevoid Update(){}
}

*这里要注意,如果只需要返回给需要的客户端,用方法2即可

4,客户端测试部分

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 Face.SocketClient
{/// <summary>/// Socket客户端/// </summary>public class SocketClient{private string ipAddressStr = "127.0.0.1";//IP地址字符串private int port = 5500;//端口#region 内部成员private Socket _socket = null;private bool _isRec = true;private bool _IsRun = false;public bool IsRun { get { return _IsRun; } }private bool IsSocketConnected(){bool part1 = _socket.Poll(1000, SelectMode.SelectRead);bool part2 = (_socket.Available == 0);if (part1 && part2)return false;elsereturn true;}/// <summary>/// 开始接受客户端消息/// </summary>public void StartRecMsg(){try{byte[] container = new byte[1024 * 1024 * 2];_socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndReceive(asyncResult);//马上进行下一轮接受,增加吞吐量if (length > 0 && _isRec && IsSocketConnected())StartRecMsg();if (length > 0){byte[] recBytes = new byte[length];Array.Copy(container, 0, recBytes, 0, length);string msgJson = Encoding.UTF8.GetString(recBytes);if (msgJson.Contains("¤€") && msgJson.Contains("€¤")){string[] arrymsg = msgJson.Replace("¤€", "卍").Split('卍');foreach (string msgitem in arrymsg){if (string.IsNullOrEmpty(msgitem))continue;if (msgitem.Substring(msgitem.Length - 2, 2) == "€¤"){string msgitemjson = msgitem.Substring(0, msgitem.Length - 2);//处理消息HandleRecMsg?.Invoke(msgitemjson, this);}}}else{HandleException?.Invoke(new Exception($"接收到错误指令,具体指令为:{msgJson}"));}}elseClose();}catch (Exception ex){if (ex.Message.Contains("远程主机强迫关闭")){_IsRun = false;}HandleException?.Invoke(ex);Close();}}, null);}catch (Exception ex){if (ex.Message.Contains("远程主机强迫关闭")){_IsRun = false;}HandleException?.Invoke(ex);Close();}}#endregion#region 外部接口/// <summary>/// 开始服务,连接服务端/// </summary>public void StartClient(){try{//实例化 套接字 (ip4寻址协议,流式传输,TCP协议)_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建 ip对象IPAddress address = IPAddress.Parse(ipAddressStr);//创建网络节点对象 包含 ip和portIPEndPoint endpoint = new IPEndPoint(address, port);//将 监听套接字  绑定到 对应的IP和端口_socket.BeginConnect(endpoint, asyncResult =>{try{_socket.EndConnect(asyncResult);//开始接受服务器消息StartRecMsg();_IsRun = true;HandleClientStarted?.Invoke(this);}catch (Exception ex){_IsRun = false;StartException?.Invoke(ex);}}, null);}catch (Exception ex){_IsRun = false;StartException?.Invoke(ex);}}/// <summary>/// 发送数据/// </summary>/// <param name="bytes">数据字节</param>private void Send(byte[] bytes){try{//Thread.Sleep(250);_socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult =>{try{int length = _socket.EndSend(asyncResult);HandleSendMsg?.Invoke(bytes, this);}catch (Exception ex){HandleException?.Invoke(ex);}}, null);}catch (Exception ex){HandleException?.Invoke(ex);}}/// <summary>/// 发送字符串(默认使用UTF-8编码)/// </summary>/// <param name="msgStr">字符串</param>public void Send(string msgStr){Send(Encoding.UTF8.GetBytes("¤€" + msgStr + "€¤"));}/// <summary>/// 发送字符串(使用自定义编码)/// </summary>/// <param name="msgStr">字符串消息</param>/// <param name="encoding">使用的编码</param>public void Send(string msgStr, Encoding encoding){Send(encoding.GetBytes("¤€" + msgStr + "€¤"));}/// <summary>/// 传入自定义属性/// </summary>public object Property { get; set; }/// <summary>/// 关闭与服务器的连接/// </summary>public void Close(){try{_isRec = false;_socket.Disconnect(false);HandleClientClose?.Invoke(this);}catch (Exception ex){HandleException?.Invoke(ex);}}#endregion#region 事件处理/// <summary>/// 客户端连接建立后回调/// </summary>public Action<SocketClient> HandleClientStarted { get; set; }/// <summary>/// 处理接受消息的委托/// </summary>public Action<string, SocketClient> HandleRecMsg { get; set; }/// <summary>/// 客户端连接发送消息后回调/// </summary>public Action<byte[], SocketClient> HandleSendMsg { get; set; }/// <summary>/// 客户端连接关闭后回调/// </summary>public Action<SocketClient> HandleClientClose { get; set; }/// <summary>/// 启动时报错误/// </summary>public Action<Exception> StartException { get; set; }/// <summary>/// 异常处理程序/// </summary>public Action<Exception> HandleException { get; set; }#endregion}}
using Coldairarrow.Util.Sockets;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class MyClient : MonoBehaviour
{private SocketClient client;public string test = "hellow222";// Start is called before the first frame updatevoid Start(){client = new SocketClient() ;client.StartClient();client.Send(test);}// Update is called once per framevoid Update(){}
}

5,测试结果

服务器:

客户端1:

客户端2:

相关文章:

C#网络连接:TCP/IP模式下的网络连接与同步

1&#xff0c;目的 为了测试局域网的消息同步&#xff0c;简单写了下TCP/IP模式的同步&#xff0c;参考这个帖子。 2&#xff0c;核心库部分 using System; using System.Net; using System.Net.Sockets; using System.Text;namespace Coldairarrow.Util.Sockets {/// <s…...

基于树莓派(Raspberry Pi) 的智能电表监测系统设计:集成 Home Assistant、SQLite 和 MQTT 协议

在全球对可持续发展和能源节约的关注日益加深的背景下&#xff0c;智能能源管理系统&#xff08;IEMS&#xff09;应运而生。该系统利用现代科技&#xff08;如物联网、云计算和大数据分析&#xff09;来优化能源使用&#xff0c;提高能效&#xff0c;降低能源成本。本文将详细…...

C语言程序设计(二)

四.找素数 素数&#xff1a;除了1和它本身不再有其他因数的自然数。换句话说&#xff1a;一个大于1的自然数 &#xff0c;如果只能被1和它本身整除&#xff0c;那就是素数&#xff08;质数&#xff09;。 在打印中遇到的问题就是&#xff0c;知道怎么写却总是运行不起来。主要…...

Oracle对数据库行和数据库的监控

前言&#xff1a; Oracle对表的监控分为数据行修改DML的监控、对表的DDL监控 1、对表的DML监控&#xff08;数据的增删改&#xff09; -- 创建测试表 create table tab_test01( id varchar2(100) default sys_guid(), name varchar2(100), insert_date date default sysdate…...

论文阅读:面向自动驾驶场景的多目标点云检测算法

论文地址:面向自动驾驶场景的多目标点云检测算法 概要 点云在自动驾驶系统中的三维目标检测是关键技术之一。目前主流的基于体素的无锚框检测算法通常采用复杂的二阶段修正模块,虽然在算法性能上有所提升,但往往伴随着较大的延迟。单阶段无锚框点云检测算法简化了检测流程,…...

Vite + Vue3 + TS项目配置前置路由守卫

在现代前端开发中&#xff0c;使用 Vue 3 和 TypeScript 的组合是一种流行且高效的开发方式。Vite 是一个极速的构建工具&#xff0c;可以显著提升开发体验。本文博主将指导你如何在 Vite Vue 3 TypeScript 项目中配置前置路由守卫&#xff08;Navigation Guards&#xff09;…...

设计模式-备忘录

备忘录&#xff08;Memento&#xff09;设计模式是为了保存对象当前状态&#xff0c;并在需要的时候恢复到之前保存的状态。以下是一个简单的C#备忘录模式的实现&#xff1a; // Originator 类&#xff0c;负责创建和恢复备忘录 class Originator {private string state;publi…...

openEuler安装docker,加速镜像拉取

文章目录 文章来源1.配置镜像源2.编辑配置文件3.安装想要的版本4. ~ 原神&#xff01;5.由于很多镜像无法拉取配置镜像源 文章来源 http://t.csdnimg.cn/zYDYy 原文连接 由于之前的仓库不让用且 1.配置镜像源 由于 国外的镜像仓库好多不让用 所以配置阿里的镜像源 yum-confi…...

angular入门基础教程(七)系统路由

路由的实现 当我们系统越来复杂&#xff0c;功能越来越多&#xff0c;路由也就是必须的了。在 ng 中如何实现路由呢&#xff1f; 启用路由 在 app 目录下&#xff0c;新建一个 router 目录&#xff0c;把 app.routers.ts 文件拷贝过来&#xff0c;并修改一下。 import { Ro…...

Unity Canvas动画:UI元素的动态展示

在Unity中&#xff0c;Canvas是用于管理和展示用户界面&#xff08;UI&#xff09;元素的系统。Canvas动画是UI设计中的重要组成部分&#xff0c;它能够提升用户体验&#xff0c;使界面更加生动和响应用户操作。本文将探讨Unity Canvas动画的基本概念、实现方法以及一些实用的技…...

apache.commons.pool2 使用指南

apache.commons.pool2 使用指南 为什么要使用池 创建对象耗时较长&#xff0c;多线程频繁调用等因素限制了我们不能每次使用时都重新创建对象&#xff0c;使用池化思想将对象放进池内&#xff0c;不同线程使用同一个池来获取对象&#xff0c;极大的减少每次业务的调用时间。 …...

【Python面试题收录】Python编程基础练习题②(数据类型+文件操作+时间操作)

本文所有代码打包在Gitee仓库中https://gitee.com/wx114/Python-Interview-Questions 一、数据类型 第一题 编写一个函数&#xff0c;实现&#xff1a;先去除左右空白符&#xff0c;自动检测输入的数据类型&#xff0c;如果是整数就转换成二进制形式并返回出结果&#xff1b…...

typescript 定义类型

type infoType string; let name: infoType "全易"; let location: infoType "北京"; // let age: infoType 18; // 报错 infoType string&#xff5c;number 就不报错了 let job: infoType "开发"; let love: infoType "吃喝玩乐&q…...

基于Java+SpringBoot+Vue的的课程作业管理系统

前言 ✌全网粉丝20W,csdn特邀作者、博客专家、CSDN[新星计划]导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取项目下载方式&#x1f345; 哈喽兄弟们&#xff0c;好久不见哦&#xff5…...

分布式日志分析系统--ELK

文章目录 ELK概述ELK主要特点ELK应用架构 Elasticsearch原理JSON格式倒排索引 ES与关系型数据库ES相关概念ES安装说明1.环境初始化2.优化系统资源限制配置3.编辑ES服务文件elasticsearch. yml 优化ELK集群安装脚本scp的使用集群安装成功 Shell命令API使用创建索引创建Type创建分…...

Linux初学基本命令

linux文件目录 1、bin->usr/bin binary存放命令 所有账户可以使用 Linux可以执行的文件&#xff0c;我们称之为命令command 2、boot 存放系统启动文件 3、dev device存放设备文件 4、etc 存放配置文件的目录 configration files 5、home home家目录 存…...

如何优化PyTorch以加快模型训练速度?

PyTorch是当今生产环境中最流行的深度学习框架之一。随着模型变得日益复杂、数据集日益庞大&#xff0c;优化模型训练性能对于缩短训练时间和提高生产力变得至关重要。 本文将分享几个最新的性能调优技巧&#xff0c;以加速跨领域的机器学习模型的训练。这些技巧对任何想要使用…...

用最简单的方法对大数据进行处理 vs spark(不需要安装大数据处理工具)

一、大文件处理策略 &#xff08;一&#xff09;、难点 内存管理&#xff1a; 大文件无法一次性加载到内存中&#xff0c;因为这可能会导致内存溢出&#xff08;OutOfMemoryError&#xff09;。 因此&#xff0c;需要使用流&#xff08;Stream&#xff09;或缓冲区&#xff08…...

非线性校正算法在红外测温中的应用

非线性校正算法在红外测温中用于修正传感器输出与实际温度之间的非线性关系。红外传感器的输出信号&#xff08;通常是电压或电流&#xff09;与温度的关系理论上是线性的&#xff0c;但在实际应用中&#xff0c;由于传感器特性的限制&#xff0c;这种关系往往呈现出非线性。非…...

python----线程、进程、协程的区别及多线程详解

文章目录 一、线程、进程、协程区别二、创建线程1、函数创建2、类创建 三、线程锁1、Lock2、死锁2.1加锁之后处理业务逻辑&#xff0c;在释放锁之前抛出异常&#xff0c;这时的锁没有正常释放&#xff0c;当前的线程因为异常终止了&#xff0c;就会产生死锁。2.2开启两个或两个…...

KubeSphere 容器平台高可用:环境搭建与可视化操作指南

Linux_k8s篇 欢迎来到Linux的世界&#xff0c;看笔记好好学多敲多打&#xff0c;每个人都是大神&#xff01; 题目&#xff1a;KubeSphere 容器平台高可用&#xff1a;环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...

脑机新手指南(八):OpenBCI_GUI:从环境搭建到数据可视化(下)

一、数据处理与分析实战 &#xff08;一&#xff09;实时滤波与参数调整 基础滤波操作 60Hz 工频滤波&#xff1a;勾选界面右侧 “60Hz” 复选框&#xff0c;可有效抑制电网干扰&#xff08;适用于北美地区&#xff0c;欧洲用户可调整为 50Hz&#xff09;。 平滑处理&…...

逻辑回归:给不确定性划界的分类大师

想象你是一名医生。面对患者的检查报告&#xff08;肿瘤大小、血液指标&#xff09;&#xff0c;你需要做出一个**决定性判断**&#xff1a;恶性还是良性&#xff1f;这种“非黑即白”的抉择&#xff0c;正是**逻辑回归&#xff08;Logistic Regression&#xff09;** 的战场&a…...

8k长序列建模,蛋白质语言模型Prot42仅利用目标蛋白序列即可生成高亲和力结合剂

蛋白质结合剂&#xff08;如抗体、抑制肽&#xff09;在疾病诊断、成像分析及靶向药物递送等关键场景中发挥着不可替代的作用。传统上&#xff0c;高特异性蛋白质结合剂的开发高度依赖噬菌体展示、定向进化等实验技术&#xff0c;但这类方法普遍面临资源消耗巨大、研发周期冗长…...

vscode(仍待补充)

写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh&#xff1f; debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

全球首个30米分辨率湿地数据集(2000—2022)

数据简介 今天我们分享的数据是全球30米分辨率湿地数据集&#xff0c;包含8种湿地亚类&#xff0c;该数据以0.5X0.5的瓦片存储&#xff0c;我们整理了所有属于中国的瓦片名称与其对应省份&#xff0c;方便大家研究使用。 该数据集作为全球首个30米分辨率、覆盖2000–2022年时间…...

【python异步多线程】异步多线程爬虫代码示例

claude生成的python多线程、异步代码示例&#xff0c;模拟20个网页的爬取&#xff0c;每个网页假设要0.5-2秒完成。 代码 Python多线程爬虫教程 核心概念 多线程&#xff1a;允许程序同时执行多个任务&#xff0c;提高IO密集型任务&#xff08;如网络请求&#xff09;的效率…...

纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join

纯 Java 项目&#xff08;非 SpringBoot&#xff09;集成 Mybatis-Plus 和 Mybatis-Plus-Join 1、依赖1.1、依赖版本1.2、pom.xml 2、代码2.1、SqlSession 构造器2.2、MybatisPlus代码生成器2.3、获取 config.yml 配置2.3.1、config.yml2.3.2、项目配置类 2.4、ftl 模板2.4.1、…...

vulnyx Blogger writeup

信息收集 arp-scan nmap 获取userFlag 上web看看 一个默认的页面&#xff0c;gobuster扫一下目录 可以看到扫出的目录中得到了一个有价值的目录/wordpress&#xff0c;说明目标所使用的cms是wordpress&#xff0c;访问http://192.168.43.213/wordpress/然后查看源码能看到 这…...

群晖NAS如何在虚拟机创建飞牛NAS

套件中心下载安装Virtual Machine Manager 创建虚拟机 配置虚拟机 飞牛官网下载 https://iso.liveupdate.fnnas.com/x86_64/trim/fnos-0.9.2-863.iso 群晖NAS如何在虚拟机创建飞牛NAS - 个人信息分享...