当前位置: 首页 > 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开启两个或两个…...

【人工智能】神经网络的优化器optimizer(二):Adagrad自适应学习率优化器

一.自适应梯度算法Adagrad概述 Adagrad&#xff08;Adaptive Gradient Algorithm&#xff09;是一种自适应学习率的优化算法&#xff0c;由Duchi等人在2011年提出。其核心思想是针对不同参数自动调整学习率&#xff0c;适合处理稀疏数据和不同参数梯度差异较大的场景。Adagrad通…...

《Playwright:微软的自动化测试工具详解》

Playwright 简介:声明内容来自网络&#xff0c;将内容拼接整理出来的文档 Playwright 是微软开发的自动化测试工具&#xff0c;支持 Chrome、Firefox、Safari 等主流浏览器&#xff0c;提供多语言 API&#xff08;Python、JavaScript、Java、.NET&#xff09;。它的特点包括&a…...

在四层代理中还原真实客户端ngx_stream_realip_module

一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡&#xff08;如 HAProxy、AWS NLB、阿里 SLB&#xff09;发起上游连接时&#xff0c;将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后&#xff0c;ngx_stream_realip_module 从中提取原始信息…...

将对透视变换后的图像使用Otsu进行阈值化,来分离黑色和白色像素。这句话中的Otsu是什么意思?

Otsu 是一种自动阈值化方法&#xff0c;用于将图像分割为前景和背景。它通过最小化图像的类内方差或等价地最大化类间方差来选择最佳阈值。这种方法特别适用于图像的二值化处理&#xff0c;能够自动确定一个阈值&#xff0c;将图像中的像素分为黑色和白色两类。 Otsu 方法的原…...

ESP32 I2S音频总线学习笔记(四): INMP441采集音频并实时播放

简介 前面两期文章我们介绍了I2S的读取和写入&#xff0c;一个是通过INMP441麦克风模块采集音频&#xff0c;一个是通过PCM5102A模块播放音频&#xff0c;那如果我们将两者结合起来&#xff0c;将麦克风采集到的音频通过PCM5102A播放&#xff0c;是不是就可以做一个扩音器了呢…...

uniapp微信小程序视频实时流+pc端预览方案

方案类型技术实现是否免费优点缺点适用场景延迟范围开发复杂度​WebSocket图片帧​定时拍照Base64传输✅ 完全免费无需服务器 纯前端实现高延迟高流量 帧率极低个人demo测试 超低频监控500ms-2s⭐⭐​RTMP推流​TRTC/即构SDK推流❌ 付费方案 &#xff08;部分有免费额度&#x…...

安卓基础(aar)

重新设置java21的环境&#xff0c;临时设置 $env:JAVA_HOME "D:\Android Studio\jbr" 查看当前环境变量 JAVA_HOME 的值 echo $env:JAVA_HOME 构建ARR文件 ./gradlew :private-lib:assembleRelease 目录是这样的&#xff1a; MyApp/ ├── app/ …...

云原生安全实战:API网关Kong的鉴权与限流详解

&#x1f525;「炎码工坊」技术弹药已装填&#xff01; 点击关注 → 解锁工业级干货【工具实测|项目避坑|源码燃烧指南】 一、基础概念 1. API网关&#xff08;API Gateway&#xff09; API网关是微服务架构中的核心组件&#xff0c;负责统一管理所有API的流量入口。它像一座…...

接口自动化测试:HttpRunner基础

相关文档 HttpRunner V3.x中文文档 HttpRunner 用户指南 使用HttpRunner 3.x实现接口自动化测试 HttpRunner介绍 HttpRunner 是一个开源的 API 测试工具&#xff0c;支持 HTTP(S)/HTTP2/WebSocket/RPC 等网络协议&#xff0c;涵盖接口测试、性能测试、数字体验监测等测试类型…...

免费数学几何作图web平台

光锐软件免费数学工具&#xff0c;maths,数学制图&#xff0c;数学作图&#xff0c;几何作图&#xff0c;几何&#xff0c;AR开发,AR教育,增强现实,软件公司,XR,MR,VR,虚拟仿真,虚拟现实,混合现实,教育科技产品,职业模拟培训,高保真VR场景,结构互动课件,元宇宙http://xaglare.c…...