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

Unity中Socket_TCP异步连接,加入断线检测以及重连功能

1、服务端

using System;
using System.Collections.Generic;
using System.Text;
#region 命名空间
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
#endregionnamespace AsynServerConsole
{/// <summary>/// Tcp协议异步通讯类(服务器端)/// </summary>public class AsynTcpServer: MonoBehaviour{//存储已连接的客户端的泛型集合private static Dictionary<string, Socket> socketList = new Dictionary<string, Socket>();private void Start(){StartListening();}float ttt;private void Update(){ttt += Time.deltaTime;if (ttt>5f){ttt = 0f;//Debug.Log("连接数量==="+ socketList.Count);if (socketList.Count > 0){foreach (var item in socketList){//  Debug.Log("连接客户端====" + item.Key);//  HandleClient(item.Value);//AsynSend(item.Value,"心跳");}}else {}}}Socket TcpServer;#region Tcp协议异步监听/// <summary>/// Tcp协议异步监听/// </summary>public void StartListening(){//主机IPIPEndPoint serverIp = new IPEndPoint(IPAddress.Parse("192.168.15.72"), 8686);TcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);TcpServer.Bind(serverIp);TcpServer.Listen(100);Debug.Log("异步开启监听...");AsynAccept(TcpServer);}#endregion#region 异步连接客户端/// <summary>/// 异步连接客户端/// </summary>/// <param name="tcpServer"></param>public void AsynAccept(Socket tcpServer){tcpServer.BeginAccept(asyncResult =>{Socket tcpClient = tcpServer.EndAccept(asyncResult);string str = tcpClient.RemoteEndPoint.ToString();socketList.Add(str, tcpClient);Debug.Log("收到连接=============" + tcpClient.RemoteEndPoint.ToString());AsynSend(tcpClient, "收到客户端连接...");//发送消息AsynAccept(tcpServer);//继续监听客户端AsynRecive(tcpClient);//继续监听客户端消息}, null);}#endregion#region 异步接受客户端消息/// <summary>/// 异步接受客户端消息/// </summary>/// <param name="tcpClient"></param>public void AsynRecive(Socket tcpClient){byte[] data = new byte[1024];try{tcpClient.BeginReceive(data, 0, data.Length, SocketFlags.None,asyncResult =>{int length = tcpClient.EndReceive(asyncResult);if (length==0){Debug.Log("客户端退出===="+tcpClient.RemoteEndPoint.ToString());foreach (var item in socketList){if (item.Key.Contains(tcpClient.RemoteEndPoint.ToString())){socketList.Remove(item.Key);}}return;}Debug.Log(tcpClient.RemoteEndPoint.ToString()+"收到客户端消息:{length}=====" + length + "___" + Encoding.UTF8.GetString(data)); AsynSend(tcpClient, "收到客户端消息...");AsynRecive(tcpClient);}, null);}catch (Exception ex){Debug.Log("异常信息:" + ex.Message);}}#endregion#region 异步发送消息/// <summary>/// 异步发送消息/// </summary>/// <param name="tcpClient">客户端套接字</param>/// <param name="message">发送消息</param>public void AsynSend(Socket tcpClient, string message){byte[] data = Encoding.UTF8.GetBytes(message);try{tcpClient.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>{//完成发送消息int length = tcpClient.EndSend(asyncResult);Debug.Log("服务端完成发送消息=====" + length+"___" +message);}, null);}catch (Exception ex){Debug.Log("发送消息异常信息=====" + ex.Message);}}#endregionprivate void HandleClient(Socket clientSocket){byte[] buffer = new byte[1024];try{int bytesRead = clientSocket.Receive(buffer);if (bytesRead > 0){// 处理接收到的数据Debug.Log("Received: {0}" + Encoding.ASCII.GetString(buffer, 0, bytesRead));}else{// 客户端正常关闭连接Debug.Log("Client closed the connection.");}}catch (SocketException se){// 处理客户端断开连接的情况Debug.Log($"Socket error: {se.Message}");}finally{// 关闭SocketclientSocket.Close();}}private void OnDestroy(){Debug.Log(socketList.Count);foreach (KeyValuePair<string, Socket> item in socketList){item.Value.Dispose();item.Value.Close();}if (TcpServer.Connected){TcpServer.Shutdown(SocketShutdown.Both);}TcpServer.Dispose();TcpServer.Close();}[ContextMenu("客户端数量")]public void DebugClientCount() {Debug.Log("连接数量===" + socketList.Count);}}
}
http://www.lryc.cn/news/452532.html

相关文章:

  • Android build子系统(01)Ninja构建系统解读
  • 徐老师的吉祥数
  • 使用html写一个能发起请求的登录界面
  • 五子棋双人对战项目(2)——登录模块
  • 几种操作系统和几种cpu
  • [Cocoa]_[初级]_[使用NSNotificationCenter作为目标观察者实现时需要注意的事项]
  • 彩虹易支付最新版源码及安装教程(修复BUG+新增加订单投诉功能)
  • ping香港服务器超时的原因通常有哪些?
  • 书生大模型实战(从入门到进阶)L3-彩蛋岛-InternLM 1.8B 模型 Android 端侧部署实践
  • setState是同步更新还是异步更新
  • TCP 流量控制 - 滑动窗口和拥塞控制算法解析
  • MongoDB聚合操作及索引底层原理
  • C++ | Leetcode C++题解之第454题四数相加II
  • 【从零开始实现stm32无刷电机FOC】【实践】【7.2/7 完整代码编写】
  • 谷歌收录查询工具,谷歌收录查询工具的使用指南
  • vue3 拖拽插件(drag)
  • 数据结构--线性表(顺序结构)
  • 面试准备111
  • Spring 的 IOC 和 AOP 是什么,有哪些优点?解密 Spring两大核心概念:IOC与AOP的魅力所在
  • 第二百六十四节 JPA教程 - JPA查询日期参数示例
  • Spring MVC的运行流程详解
  • 判断有向图是否为单连通图的算法
  • php与python建站的区别有哪些
  • 模型评估与验证:确保模型在未知数据上的表现----示例:使用K折交叉验证评估分类模型、房价预测问题使用K折交叉验证来评估一个线性回归模型的性能
  • awd基础学习
  • C#基于SkiaSharp实现印章管理(10)
  • 通过栈实现字符串中查找是否有指定字符串的存在
  • MongoDB伪分布式部署(mac M2)
  • Golang | Leetcode Golang题解之第454题四数相加II
  • [ComfyUI]Flux:超美3D微观山水禅意,经典中文元素AI重现,佛陀楼阁山水画卷