public static CustomNet GetInstance() { if (Instance == null) { Instance = new CustomNet(); } return(Instance); }
//发往客户端 public void SendToClient(IMessage protocol, int connect_id) { if (!CustomNet.GetInstance().ExistConnect(connect_id)) { Log.Debug("玩家Socket不存在:" + connect_id); return; } Log.Debug("服务端发送消息:" + protocol.GetType() + " 数据:" + protocol.ToString()); CustomNet.GetInstance().SendData(connect_id, this.PackProtocol(protocol)); }
//发往服务器 public void SendToServer(IMessage protocol, int connect_id, int addition = 0, List <int> player_id_list = null) { if (!CustomNet.GetInstance().ExistConnect(connect_id)) { Log.Debug("服务器Socket不存在:" + connect_id); return; } Log.Debug("服务端发送消息:" + protocol.GetType() + " 数据:" + protocol.ToString()); CustomNet.GetInstance().SendData(connect_id, this.PackProtocol(protocol, addition, player_id_list)); }
private void ReceiveMsg(object obj) { Socket socket = obj as Socket; while (true) { try { byte[] data = new byte[Const.BUFFSIZE]; int length = socket.Receive(data); //Log.Debug("服务端接收消息:" + socket.RemoteEndPoint.ToString() + "长度为:" + length); int connect_id = CustomNet.GetInstance().GetConnectId(socket); if (connect_id == 0) { Exception e = new Exception("Socket对应的连接ID不存在!!!"); throw e; } if (length > 0) { CustomNet.GetInstance().AddCacheByte(socket, data, length); while (true) { byte[] msg_bytes = CustomNet.GetInstance().DivideMsg(socket); if (msg_bytes == null) { break; } this.UnPackProtocol(msg_bytes, connect_id); } } else { Exception e = new Exception(string.Format("Socket已断开连接 ConnectId:{0}!!!", connect_id)); throw e; } } catch (Exception e) { Log.Debug(e.ToString()); socket.Shutdown(SocketShutdown.Both); socket.Close(); break; } } }
private void ConnectListen(object obj) { Socket socket = obj as Socket; while (true) { Socket accept_socket = socket.Accept(); accept_socket.ReceiveBufferSize = Const.BUFFSIZE; accept_socket.SendBufferSize = Const.BUFFSIZE; CustomNet.GetInstance().AddSocket(accept_socket); Log.Debug("Socket连接成功:" + accept_socket.RemoteEndPoint.ToString()); Thread thread = new Thread(this.connect_callback); thread.IsBackground = true; thread.Start(accept_socket); } }
//把自身信息注册到路由服 public void RegisterToRoute() { SRRegisterServer protocol = new SRRegisterServer(); protocol.ServerId = this.server_info.ServerId; protocol.ServerType = this.server_info.ServerType; foreach (int scene_id in this.server_info.SceneIdList) { protocol.SceneIdList.Add(scene_id); } List <int> connect_list = CustomNet.GetInstance().GetConnectList(); foreach (int connect_id in connect_list) { Log.DebugFormat("Send To Route ConnectId:{0}", connect_id); this.socket.SendToServer(protocol, connect_id); } }
public void Release() { CustomNet.GetInstance().Release(); }
public void Connect(string ip, int port) { CustomNet.GetInstance().Connect(ip, port, ReceiveMsg); }
public void Listen(string ip, int port) { CustomNet.GetInstance().Listen(ip, port, ReceiveMsg); }