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

news/2024/9/22 17:23:04/

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:


http://www.ppmy.cn/news/1501883.html

相关文章

Spark RPC框架详解

文章目录 前言Spark RPC模型概述RpcEndpointRpcEndpointRefRpcEnv 基于Netty的RPC实现NettyRpcEndpointRefNettyRpcEnv消息的发送消息的接收RpcEndpointRef的构造方式直接通过RpcEndpoint构造RpcEndpointRef通过消息发送RpcEndpointRef Endpoint的注册Dispatcher消息的投递消息…

C语言经典习题24

文件操作习题 一 编程删除从C盘home文件夹下data.txt文本文件中所读取字符串中指定的字符&#xff0c;该指定字符由键盘输入&#xff0c;并将修改后的字符串以追加方式写入到文本文件C:\home\data.txt中。 #include<stdio.h> main() { char s[100],ch; int i;…

PHP苹果 V X iPhone微商i o s多分开V X语音转发密友朋友圈一键跟圈软件

苹果VX神器&#xff01;iPhone微商必备&#xff1a;ios多开、VX语音转发、密友朋友圈一键跟圈软件大揭秘&#xff01; 一、iOS多开新境界&#xff0c;工作生活两不误&#xff01; 你是不是也烦恼过&#xff0c;想要在工作号和生活号之间自由切换&#xff0c;却因为iPhone的限制…

Git 分布式版本控制系统、创建分支,跳转分支、git拉取、在码云上创建项目,进行pull 和 push、克隆码云上任意项目

目录 1.Git 分布式版本控制系统&#xff1a; 1.安装git 2.创建目录&#xff0c;进行初始化 3.写入Java文件&#xff0c;提交文件 4.文件放入仓库 2.创建分支&#xff0c;跳转分支&#xff08;所有的git操作都应该工作在&#xff0c;指定的init 目录下进行&#xff09; 1.…

javascript(二)

三、选择器 1.选择器的种类 document.getElementById() 通过id来查找元素 document.getElementsByTagName() 通过标签来查找元素 document.getElementsByClassName() 通过类名&#xff08;class&#xff09;来查找元素 document.getElementsByName() 通过name来查找元…

Sonatype Nexus Repository搭建与使用(详细教程3.70.1)

目录 一. 环境准备 二. 安装jdk 三. 搭建Nexus存储库 四. 使用介绍 一. 环境准备 主机名IP系统软件版本配置信息nexus192.168.226.26Rocky_linux9.4 Nexus Repository 3.70.1 MySQL8.0 jdk-11.0.23 2核2G&#xff0c;磁盘20G 进行时间同步&#xff0c;关闭防火墙和selinux…

学习笔记-系统框图传递函数公式推导

目录 *待了解 现代控制理论和自动控制理论区别 自动控制系统的组成 信号流图 1、系统框图 1.1、信号线、分支点、相加点 1.2、系统各环节间的连接 1.3、 相加点和分支点的等效移动&#xff08;比较点、引出点&#xff09; 2、反馈连接公式推导 2.1、前向通路传递函数…

旷野之间32 - OpenAI 拉开了人工智能竞赛的序幕,而Meta 将会赢得胜利

他们通过故事做到了这一点&#xff08;Snapchat 是第一个&#xff09;他们用 Reels 实现了这个功能&#xff08;TikTok 是第一个实现这个功能的&#xff09;他们正在利用人工智能来实现这一点。 在人工智能竞赛开始时&#xff0c;Meta 的人工智能平台的表现并没有什么特别值得…