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

浅谈 React Hooks

React Hooks 是 React 16.8 引入的一组 API&#xff0c;用于在函数组件中使用 state 和其他 React 特性&#xff08;例如生命周期方法、context 等&#xff09;。Hooks 通过简洁的函数接口&#xff0c;解决了状态与 UI 的高度解耦&#xff0c;通过函数式编程范式实现更灵活 Rea…...

未来机器人的大脑:如何用神经网络模拟器实现更智能的决策?

编辑&#xff1a;陈萍萍的公主一点人工一点智能 未来机器人的大脑&#xff1a;如何用神经网络模拟器实现更智能的决策&#xff1f;RWM通过双自回归机制有效解决了复合误差、部分可观测性和随机动力学等关键挑战&#xff0c;在不依赖领域特定归纳偏见的条件下实现了卓越的预测准…...

反向工程与模型迁移:打造未来商品详情API的可持续创新体系

在电商行业蓬勃发展的当下&#xff0c;商品详情API作为连接电商平台与开发者、商家及用户的关键纽带&#xff0c;其重要性日益凸显。传统商品详情API主要聚焦于商品基本信息&#xff08;如名称、价格、库存等&#xff09;的获取与展示&#xff0c;已难以满足市场对个性化、智能…...

centos 7 部署awstats 网站访问检测

一、基础环境准备&#xff08;两种安装方式都要做&#xff09; bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats&#xff0…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容

基于 ​UniApp + WebSocket​实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配​微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...

【2025年】解决Burpsuite抓不到https包的问题

环境&#xff1a;windows11 burpsuite:2025.5 在抓取https网站时&#xff0c;burpsuite抓取不到https数据包&#xff0c;只显示&#xff1a; 解决该问题只需如下三个步骤&#xff1a; 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

ServerTrust 并非唯一

NSURLAuthenticationMethodServerTrust 只是 authenticationMethod 的冰山一角 要理解 NSURLAuthenticationMethodServerTrust, 首先要明白它只是 authenticationMethod 的选项之一, 并非唯一 1 先厘清概念 点说明authenticationMethodURLAuthenticationChallenge.protectionS…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...

JAVA后端开发——多租户

数据隔离是多租户系统中的核心概念&#xff0c;确保一个租户&#xff08;在这个系统中可能是一个公司或一个独立的客户&#xff09;的数据对其他租户是不可见的。在 RuoYi 框架&#xff08;您当前项目所使用的基础框架&#xff09;中&#xff0c;这通常是通过在数据表中增加一个…...