public void init() { SFUtils.log("正在连接GameServer..."); m_sendQueue = new Queue <SFBaseRequestMessage>(); m_recvQueue = new Queue <string>(); dispatcher = new SFEventDispatcher(this); m_client = new SFTcpClient(); m_ping = -1; m_heartbeatTimer = SFCommonConf.instance.heatbeatInterval; m_client.init(SFCommonConf.instance.serverIp, SFCommonConf.instance.serverPort, onRecvMsg, ret => { if (ret == 0) { SFUtils.log("连接GameServer成功"); } else { SFUtils.logWarning("连接GameServer失败"); } dispatcher.dispatchEvent(SFEvent.EVENT_NETWORK_READY, new SFSimpleEventData(ret)); }); m_client.dispatcher.addEventListener(this, SFEvent.EVENT_NETWORK_INTERRUPTED, e => { dispatcher.dispatchEvent(e); }); dispatcher.addEventListener(this, SFResponseMsgSocketHeartbeat.pName, onHeartbeat); }
void handleProtocol(int pid, string jsonData) { // 这个方法应该由主线程调用 try { string pName = string.Format("socket_{0}", pid); SFBaseResponseMessage obj = null; if (pid == int.MaxValue) { } // __start__ else if (pid == 0) { obj = JsonUtility.FromJson <SFResponseMsgSocketHeartbeat>(jsonData); } else if (pid == 1) { obj = JsonUtility.FromJson <SFResponseMsgUnitLogin>(jsonData); } else if (pid == 2) { obj = JsonUtility.FromJson <SFResponseMsgNotifyRemoteUsers>(jsonData); } else if (pid == 3) { obj = JsonUtility.FromJson <SFResponseMsgUnitSync>(jsonData); } else if (pid == 4) { obj = JsonUtility.FromJson <SFResponseMsgNotifyUnitStatus>(jsonData); } else if (pid == 5) { obj = JsonUtility.FromJson <SFResponseMsgNotifyNewUserJoin>(jsonData); } else if (pid == 6) { obj = JsonUtility.FromJson <SFResponseMsgHostRoom>(jsonData); } else if (pid == 7) { obj = JsonUtility.FromJson <SFResponseMsgJoinRoom>(jsonData); } else // __end__ { SFUtils.logWarning("不能识别的协议号: {0}", pid); } if (obj != null) { dispatcher.dispatchEvent(pName, obj); } } catch (Exception e) { SFUtils.logWarning("解析协议失败: {0}\ndata: {1}\n错误信息:{2}\n出错方法:{3}", pid, jsonData, e.Message, e.StackTrace); } }
void socketRecv() { if (m_socket.Connected && m_isReady) { byte[] data = new byte[1024]; // 以1024字节为单位接收数据 m_socket.BeginReceive(data, 0, data.Length, SocketFlags.None, result => { try { int length = m_socket.EndReceive(result); m_totalRecv += length; // 解码并执行回调 if (length > 0) { string str = Encoding.UTF8.GetString(data); onRecvMsg(str, length); socketRecv(); } else { throw new Exception("Socket recv 0 byte"); } } catch (Exception e) { uninit(); SFUtils.logWarning("网络连接中断:" + e.Message); dispatcher.dispatchEvent(SFEvent.EVENT_NETWORK_INTERRUPTED); } }, null); } }