using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Linq; using UnityEngine; using UnityEngine.Events; public class Conn { UnityAction closeEvent;//断开连接事件 //缓冲区最大长度 public const int BufferSize = 16384; //通信基类 public Socket socket; //当前数据长度 public int bufferCount; //当前对象是否使用 public bool isUse = false; //字节码缓冲区 public byte[] readBuffer; //消息长度 public int msgLength = 0; //最后一次心跳时间 public long lastTickTime; public byte[] lenBytes = new byte[sizeof(UInt32)]; string endPoint; //创建时确定缓冲区大小 public Conn() { readBuffer = new byte[BufferSize]; } //获取连接该对象的客户终端地址 public string GetEndIPDress() { if (!isUse) return "该对象未启用,获取地址失败"; return endPoint; } //关闭连接 public void Close() { if (!isUse) return; //Debug.Log($"{endPoint}断开链接"); //MessageBox.Show("断开:"+GetEndIPDress()); socket.Shutdown(SocketShutdown.Both); socket.Close(); isUse = false; closeEvent?.Invoke(endPoint); endPoint = null; } //启用时初始化Conn public void Init(Socket socket,UnityAction closeAction) { this.socket = socket; isUse = true; bufferCount = 0; lastTickTime = SysTime.GetTimeStamp(); endPoint = socket.RemoteEndPoint.ToString().Split(':')[0];//获取目标的IP [1]为端口 closeEvent = closeAction; } //缓冲区剩余长度 public int BuffRemain() { return BufferSize - bufferCount; } public void Send(ProtocolBase protocolBase) { byte[] bytes = protocolBase.Encode(); byte[] length = BitConverter.GetBytes(bytes.Length); byte[] sendBuff = length.Concat(bytes).ToArray(); socket.Send(sendBuff); } }