using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace GeneralTools { public class SocketManager : SingletonBaseAttribute { private List socketList; public override void IAwake() { socketList = new List(); } public SocketBase GetSocketByName(string socketName) { for (int i = 0; i < socketList.Count; i++) { if (socketList[i] != null && socketList[i].GetSocketName() == socketName) { return socketList[i]; } } return null; } private void Update() { if (socketList == null) return; //处理所有创建的socket消息事件 for (int i = 0; i < socketList.Count; i++) { if(socketList[i]!=null) { socketList[i].DoReceiveEvent(); socketList[i].SetNowTime(Time.realtimeSinceStartup); } } } /// /// 创建TCP服务器,绑定自身IP和端口 /// /// /// public SocketBase CreateTcpSever(string ip, int port) { SocketBase newSever = new TCPServer(ip, port); AddToSocketList(newSever); return newSever; } /// /// 创建TCP服务器,绑定端口 /// /// /// public SocketBase CreateTcpSever(int port) { SocketBase newSever = new TCPServer("", port); AddToSocketList(newSever); return newSever; } /// /// 创建TCP客户端,指定服务器IP,端口 /// /// /// /// public SocketBase CreateTcpClient(string ip, int port) { SocketBase newClient = new TCPClient(ip, port); AddToSocketList(newClient); return newClient; } /// /// 创建UDP,指定对方IP,端口,并绑定自己端口 /// /// /// /// /// public SocketBase CreateUdp(string targetIP, int targetPort, int selfPort) { SocketBase newUdp = new UDPClient(targetIP, targetPort, selfPort); AddToSocketList(newUdp); return newUdp; } /// /// 创建UDP, 指定对方IP,端口,自身端口随机 /// /// /// /// /// public SocketBase CreateUdp(string targetIP, int targetPort) { SocketBase newUdp = new UDPClient(targetIP, targetPort, 0); AddToSocketList(newUdp); return newUdp; } /// /// 创建UDP,对指定端口广播,并绑定自身端口 /// /// /// /// public SocketBase CreateUdp(int targetPort, int selfPort) { SocketBase newUdp = new UDPClient(null, targetPort, selfPort); AddToSocketList(newUdp); return newUdp; } /// /// 创建UDP,对指定端口广播,自身端口随机 /// /// /// public SocketBase CreateUdp(int targetPort) { SocketBase newUdp = new UDPClient(null, targetPort, 0); AddToSocketList(newUdp); return newUdp; } /// /// 创建UDP,对10000端口广播,自身端口随机 /// /// /// public SocketBase CreateUdp() { SocketBase newUdp = new UDPClient(null, 10000, 0); AddToSocketList(newUdp); return newUdp; } /// /// 创建WebSocket客户端 /// /// /// public SocketBase CreateWebSocketClient(string url) { SocketBase newWebSocketClient = new WebSocketClient(url); AddToSocketList(newWebSocketClient); return newWebSocketClient; } protected void AddToSocketList(SocketBase socket) { if (socketList == null) return; int index = socketList.Count; socketList.Add(socket); socket.onSocketQuit += () => { SocketQuitHandler(index); }; } protected void SocketQuitHandler(int index) { if (socketList == null) return; if(index >= 0 && index