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

将 magma example 改写成 cusolver example eqrf

1&#xff0c;简单安装Magma 1.1 下载编译 OpenBLAS $ git clone https://github.com/OpenMathLib/OpenBLAS.git $ cd OpenBLAS/ $ make -j DEBUG1 $ make install PREFIX/home/hipper/ex_magma/local_d/OpenBLAS/1.2 下载编译 magma $ git clone https://bitbucket.org/icl…...

微信小程序教程007:数据绑定

文章目录 数据绑定1、数据绑定原则2、在data中定义页面数据3、Mustache语法的格式4、Mustache应用场景5、绑定属性6、三元运算8、算数运算数据绑定 1、数据绑定原则 在data中定义数据在WXML中使用数据2、在data中定义页面数据 在页面对应的.js文件中,把数据定义到data对象中…...

Git -- git stash 暂存

使用 git 或多或少都会了解到 git stash 命令&#xff0c;但是可能未曾经常使用&#xff0c;下面简单介绍两种使用场景。 场景一&#xff1a;分支A开发&#xff0c;分支B解决bug 我们遇到最常见的例子就是&#xff0c;在当前分支 A 上开发写需求&#xff0c;但是 B 分支上有…...

基于YOLO的植物病害识别系统:从训练到部署全攻略

基于深度学习的植物叶片病害识别系统&#xff08;UI界面YOLOv8/v7/v6/v5代码训练数据集&#xff09; 1. 引言 在农业生产中&#xff0c;植物叶片病害是影响作物产量和质量的主要因素之一。传统的病害检测方法依赖于人工识别&#xff0c;效率低且易受主观因素影响。随着深度学…...

数据库开发:MySQL基础(二)

MySQL基础&#xff08;二&#xff09; 一、表的关联关系 在关系型数据库中&#xff0c;表之间可以通过关联关系进行连接和查询。关联关系是指两个或多个表之间的关系&#xff0c;通过共享相同的列或键来建立连接。常见的关联关系有三种类型&#xff1a;一对多关系&#xff0c;…...

实现物理数据库迁移到云上

实现物理数据库迁移到云上 以下是一个PHP脚本&#xff0c;用于实现物理数据库迁移到云上的步骤&#xff1a; <?php// 评估和规划 $databaseSize "100GB"; $performanceRequirements "high"; $dataComplexity "medium";$cloudProvider &…...

[Spring] MyBatis操作数据库(进阶)

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…...

【Websim.ai】一句话让AI帮你生成一个网页

【Websim.ai】一句话让AI帮你生成一个网页 网站链接 websim.ai 简介 websim.ai接入了Claude Sonnet 3.5&#xff0c;GPT-4o等常用的LLM&#xff0c;只需要在websim.ai的官网指令栏中编写相关指令&#xff0c;有点类似大模型的Prompt&#xff0c;指令的好坏决定了网页生成的…...

云计算实训16——关于web,http协议,https协议,apache,nginx的学习与认知

一、web基本概念和常识 1.Web Web 服务是动态的、可交互的、跨平台的和图形化的为⽤户提供的⼀种在互联⽹上浏览信息的服务。 2.web服务器&#xff08;web server&#xff09; 也称HTTP服务器&#xff08;HTTP server&#xff09;&#xff0c;主要有 Nginx、Apache、Tomcat 等。…...

2024年必备技能:小红书笔记评论自动采集,零基础也能学会的方法

摘要&#xff1a; 面对信息爆炸的2024年&#xff0c;小红书作为热门社交平台&#xff0c;其笔记评论成为市场洞察的金矿。本文将手把手教你&#xff0c;即便编程零基础&#xff0c;也能轻松学会利用Python自动化采集小红书笔记评论&#xff0c;解锁营销新策略&#xff0c;提升…...

【Gitlab】SSH配置和克隆仓库

生成SSH Key ssh-keygen -t rsa -b 4096 私钥文件: id_rsa 公钥文件:id_rsa.pub 复制生成的ssh公钥到此处 克隆仓库 git clone repo-address 需要进行推送和同步来更新本地和服务器的文件 推送更新内容 git push <remote><branch> 拉取更新内容 git pull &…...

[Day 35] 區塊鏈與人工智能的聯動應用:理論、技術與實踐

區塊鏈的分布式存儲技術 區塊鏈技術自2008年比特幣白皮書發表以來&#xff0c;已經成為一種革命性的技術&#xff0c;帶來了許多創新。區塊鏈本質上是一個去中心化的分布式賬本&#xff0c;每個節點都持有賬本的副本&#xff0c;並參與記錄和驗證交易。分布式存儲是區塊鏈的重…...

Vue 3 中使用 inMap.js 实现蜂窝热力图的可视化

本文由ScriptEcho平台提供技术支持 项目地址&#xff1a;传送门 Vue 3 中使用 inMap.js 实现蜂窝热力图的可视化 应用场景介绍 蜂窝热力图是一种可视化技术&#xff0c;用于在地图上显示数据的分布情况。它将数据点划分为六边形单元格&#xff0c;并根据单元格内数据的密度…...

nginx隐藏server及版本号

1、背景 为了提高nginx服务器的安全性&#xff0c;降低被攻击的风险&#xff0c;需要隐藏nginx的server和版本号。 2、隐藏nginx版本号 在 http {—}里加上 server_tokens off; 如&#xff1a; http {……省略sendfile on;tcp_nopush on;keepalive_timeout 60;tcp_nodelay o…...

Oracle DBMS_XPLAN包

DBMS_XPLAN 包的解释和关键点 DBMS_XPLAN 包是 Oracle 数据库中一个重要的工具&#xff0c;它允许数据库管理员和开发人员以各种方式显示 SQL 语句的执行计划&#xff0c;这对于 SQL 优化和性能诊断至关重要。以下是主要函数及其描述&#xff1a; 用于显示执行计划的主要函数…...

【ffmpeg命令入门】分离音视频流

文章目录 前言音视频交错存储概念为什么要进行音视频交错存储&#xff1a;为什么要分离音视频流&#xff1a; 去除音频去除视频 总结 前言 FFmpeg 是一款强大的多媒体处理工具&#xff0c;广泛应用于音视频的录制、转换和流媒体处理等领域。它支持几乎所有的音频和视频格式&am…...

小红书笔记评论采集全攻略:三种高效方法教你批量导出

摘要&#xff1a; 本文将深入探讨如何利用Python高效采集小红书平台上的笔记评论&#xff0c;通过三种实战策略&#xff0c;手把手教你实现批量数据导出。无论是市场分析、竞品监测还是用户反馈收集&#xff0c;这些技巧都将为你解锁新效率。 一、引言&#xff1a;小红书数据…...

实战:ZooKeeper 操作命令和集群部署

ZooKeeper 操作命令 ZooKeeper的操作命令主要用于对ZooKeeper服务中的节点进行创建、查看、修改和删除等操作。以下是一些常用的ZooKeeper操作命令及其说明&#xff1a; 一、启动与连接 启动ZooKeeper服务器&#xff1a; ./zkServer.sh start这个命令用于启动ZooKeeper服务器…...

linux运维一天一个shell命令之 top详解

概念&#xff1a; top 命令是 Unix 和类 Unix 操作系统&#xff08;如 Linux、macOS&#xff09;中一个常用的系统监控工具&#xff0c;它提供了一个动态的实时视图&#xff0c;显示系统的整体性能信息&#xff0c;如 CPU 使用率、内存使用情况、进程列表等。 基本用法 root…...

大模型微调:参数高效微调(PEFT)方法总结

PEFT (Parameter-Efficient Fine-Tuning) 参数高效微调是一种针对大模型微调的技术&#xff0c;旨在减少微调过程中需要调整的参数量&#xff0c;同时保持或提高模型的性能。 以LORA、Adapter Tuning 和 Prompt Tuning 为主的PEFT方法总结如下 LORA 论文题目&#xff1a;LORA:…...

Spark+实例解读

第一部分 Spark入门 学习教程&#xff1a;Spark 教程 | Spark 教程 Spark 集成了许多大数据工具&#xff0c;例如 Spark 可以处理任何 Hadoop 数据源&#xff0c;也能在 Hadoop 集群上执行。大数据业内有个共识认为&#xff0c;Spark 只是Hadoop MapReduce 的扩展&#xff08…...

WPF多语言国际化,中英文切换

通过切换资源文件的形式实现中英文一键切换 在项目中新建Language文件夹&#xff0c;添加资源字典&#xff08;xaml文件&#xff09;&#xff0c;中文英文各一个。 在资源字典中写上想中英文切换的字符串&#xff0c;需要注意&#xff0c;必须指定key值&#xff0c;并且中英文…...

Halcon深度学习分类模型

1.Halcon20之后深度学习支持CPU训练模型&#xff0c;没有money买显卡的小伙伴有福了。但是缺点也很明显&#xff0c;就是训练速度超级慢&#xff0c;推理效果也没有GPU好&#xff0c;不过学习用足够。 2.分类模型是Halcon深度学习最简单的模型&#xff0c;可以用在物品分类&…...

洗地机哪种牌子好?洗地机排行榜前十名公布

洗地机市场上品牌琳琅满目&#xff0c;每个品牌都有其独特的魅力和优势。消费者在选择时&#xff0c;往往会根据自己的实际需求、预算以及对产品性能的期望来做出决策。因此&#xff0c;无论是哪个品牌的洗地机&#xff0c;只要能够满足用户的清洁需求&#xff0c;提供便捷的操…...

C++中的虚函数与多态机制如何工作?

在C中&#xff0c;虚函数和多态机制是实现面向对象编程的重要概念。 虚函数是在基类中声明的函数&#xff0c;可以在派生类中进行重写。当基类的指针或引用指向派生类的对象时&#xff0c;通过调用虚函数可以实现动态绑定&#xff0c;即在运行时确定要调用的函数。 多态是指通…...

《LeetCode热题100》---<哈希三道>

本篇博客讲解 LeetCode热题100道中的哈希篇中的三道题。分别是 1.第一道&#xff1a;两数之和&#xff08;简单&#xff09; 2.第二道&#xff1a;字母异位词分组&#xff08;中等&#xff09; 3.第三道&#xff1a;最长连续序列&#xff08;中等&#xff09; 第一道&#xff1…...

秒懂C++之string类(下)

目录 一.接口说明 1.1 erase 1.2 replace&#xff08;最好别用&#xff09; 1.3 find 1.4 substr 1.5 rfind 1.6 find_first_of 1.7 find_last_of 二.string类的模拟实现 2.1 构造 2.2 无参构造 2.3 析构 2.4.【】运算符 2.5 迭代器 2.6 打印 2.7 reserve扩容 …...

github简单地操作

1.调节字体大小 选择options 选择text 选择select 选择你需要的参数就可以了。 2.配置用户名和邮箱 桌面右键&#xff0c;选择git Bash Here git config --global user.name 用户名 git config --global user.email 邮箱名 3.用git实现代码管理的过程 下载别人的项目 git …...

模型改进-损失函数合集

模版 第一步在哪些地方做出修改&#xff1a; 228行 self.use_wiseiouTrue 230行 self.wiou_loss WiseIouLoss(ltypeMPDIoU, monotonousFalse, inner_iouTrue, focaler_iouFalse) 238行 wiou self.wiou_loss(pred_bboxes[fg_mask], target_bboxes[fg_mask], ret_iouFalse…...

C++模板(初阶)

1.引入 在之前的笔记中有提到&#xff1a;函数重载&#xff08;特别是交换函数&#xff08;Swap&#xff09;的实现&#xff09; void Swap(int& left, int& right) {int temp left;left right;right temp; } void Swap(double& left, double& right) {do…...