public void HandleRecv(IFFSocket ffsocket, string strData) { m_strRecvData += strData; while (m_strRecvData.Length >= 8) { byte[] btValue = Util.String2Byte(m_strRecvData); size = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(btValue, 0)); cmd = (UInt16)System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(btValue, 4)); flag = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(btValue, 6)); FFLog.Trace(string.Format("HandleRecv cmd:{0},len:{1}", cmd, size)); if (m_strRecvData.Length < 8 + size) { break; } string strMsg = m_strRecvData.Remove(0, 8); if (strMsg.Length == size) { m_strRecvData = ""; } else { strMsg = strMsg.Remove(size); m_strRecvData = m_strRecvData.Remove(0, 8 + size); } try { m_funcMsgHandler(ffsocket, cmd, strMsg); } catch (Exception ex) { FFLog.Error("scoket.HandleRecv error:" + ex.Message); } } }
public bool InitPool(string host, int nThreadNum) { m_dbForSync = new MysqlOps(); if (!m_dbForSync.Connect(host)) { FFLog.Error(string.Format("DbMgr::connectDB failed<{0}>", m_dbForSync.ErrorMsg())); m_dbForSync = null; return(false); } m_dbPool = new DBConnectionInfo[nThreadNum]; for (int i = 0; i < nThreadNum; ++i) { MysqlOps db = new MysqlOps(); if (!db.Connect(host)) { FFLog.Error(string.Format("DbMgr::connectDB failed<{0}>", db.ErrorMsg())); return(false); } m_dbPool[i] = new DBConnectionInfo() { tq = new TaskQueue(), db = db }; m_dbPool[i].tq.Run(); } FFLog.Info(string.Format("DbMgr::connectDB host<{0}>,num<{1}>", host, nThreadNum)); return(true); }
public void HandleMsg(IFFSocket ffsocket, UInt16 cmd, byte[] strMsg) { var sessionData = ffsocket.GetSessionData(); if (sessionData == null)//!first msg { string strDefaultWorker = "worker#0"; if (m_ffrpc.IsExistNode(strDefaultWorker) == false) { //ffsocket.Close(); FFLog.Error(string.Format("gate worker[{0}] not exist", strDefaultWorker)); FFNet.SendMsg(ffsocket, 256, Util.String2Byte("server is busy!0x0!你好")); return; } Int64 sessionIDNew = ++m_nIDGenerator; ClientInfo cinfo = new ClientInfo() { sockObj = ffsocket, sessionID = sessionIDNew, strAllocWorker = strDefaultWorker }; ffsocket.SetSessionData(sessionIDNew); m_dictClients[sessionIDNew] = cinfo; RouteLogicMsg(cinfo, cmd, strMsg, true); return; } Int64 sessionID = (Int64)sessionData; if (m_dictClients.ContainsKey(sessionID) == false) { return; } ClientInfo cinfo2 = m_dictClients[sessionID]; RouteLogicMsg(cinfo2, cmd, strMsg, false); }
public void HandleAccepted(IAsyncResult ar) { if (!bRunning) { return; } try { Socket socket = (Socket)ar.AsyncState; //方法参考:http://msdn.microsoft.com/zh-cn/library/system.net.sockets.socket.endreceive.aspx if (socket != null) { var client = socket.EndAccept(ar); IFFSocket ffsocket = new FFScoketAsync(m_oSocketCtrl.ForkSelf(), client); ffsocket.AsyncRecv(); FFLog.Info(string.Format("scoket: handleAccepted ip:{0}", ffsocket.GetIP())); } } catch (Exception ex) { FFLog.Error("scoket: handleAccepted Error " + ex.Message); } if (bRunning) { m_oSocket.BeginAccept(new AsyncCallback(HandleAccepted), m_oSocket); } }
public bool Call <MSG_TYPE, RET_TYPE>(string strServiceName, MSG_TYPE msgData, TCallBack <RET_TYPE> callback) where MSG_TYPE : Thrift.Protocol.TBase, new() where RET_TYPE : Thrift.Protocol.TBase, new() { if (!m_brokerData.Service2nodeId.ContainsKey(strServiceName)) { FFLog.Error(string.Format("ffrpc.Call servervice:{0} not exist", strServiceName)); RET_TYPE retMsg = new RET_TYPE(); callback(retMsg); return(false); } BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq() { CallbackId = 0, Errinfo = "" }; reqMsg.DestNodeId = m_brokerData.Service2nodeId[strServiceName]; reqMsg.DestServiceName = strServiceName; reqMsg.Body = FFNet.EncodeMsg(msgData);//Util.Byte2String( reqMsg.DestMsgName = Type2Name(msgData); reqMsg.CallbackId = ++m_nIDGenerator; m_dictCallBack[reqMsg.CallbackId] = (BrokerRouteMsgReq dataMsg) => { RET_TYPE retMsg = new RET_TYPE(); FFNet.DecodeMsg(retMsg, dataMsg.Body); callback(retMsg); }; SendToDestNode(reqMsg); return(true); }
public bool Init(string strBrokerHost, string strGateListenIpPort, int nGateIndex = 0) { m_nGateIndex = nGateIndex; m_strGateName = string.Format("gate#{0}", m_nGateIndex); m_ffrpc = new FFRpc(m_strGateName); if (m_ffrpc.Open(strBrokerHost) == false) { FFLog.Error("gate ffrpc open failed!"); return(false); } m_ffrpc.Reg <GateChangeLogicNodeReq, EmptyMsgRet>(this.ChangeSessionLogic); m_ffrpc.Reg <GateCloseSessionReq, EmptyMsgRet>(this.CloseSession); m_ffrpc.Reg <GateRouteMsgToSessionReq, EmptyMsgRet>(this.RouteMsgToSession); m_ffrpc.Reg <GateBroadcastMsgToSessionReq, EmptyMsgRet>(this.BroadcastMsgToSession); m_acceptor = FFNet.Listen(strGateListenIpPort, new SocketMsgHandler(HandleMsg), new SocketBrokenHandler(HandleBroken)); if (m_acceptor != null) { FFLog.Trace(string.Format("FFGate open....{0} ok", strGateListenIpPort)); } else { FFLog.Error(string.Format("FFGate open....{0} failed", strGateListenIpPort)); } return(true); }
public bool Init(string strBrokerHost, int nWorkerIndex, string[] listEnableClassNames) { m_nWorkerIndex = nWorkerIndex; m_strWorkerName = string.Format("worker#{0}", m_nWorkerIndex); m_ffrpc = new FFRpc(m_strWorkerName); if (m_ffrpc.Open(strBrokerHost) == false) { FFLog.Error("worker ffrpc open failed!"); return(false); } m_ffrpc.Reg <RouteLogicMsgReq, EmptyMsgRet>(this.OnRouteLogicMsgReq); m_ffrpc.Reg <SessionOfflineReq, EmptyMsgRet>(this.OnSessionOfflineReq); m_ffrpc.Reg <SessionEnterWorkerReq, EmptyMsgRet>(this.OnSessionEnterWorkerReq); string err = Util.InitClassByNames(listEnableClassNames); if (err != "") { FFLog.Error("worker init failed mod=" + err); return(false); } m_listEnableClassNames = listEnableClassNames; return(true); }
static public void Theout() { FFLog.Trace(string.Format("theout! {0}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString())); FFLog.Debug("AAAAAAAAAAAAAAA1"); FFLog.Trace("AAAAAAAAAAAAAAA2"); FFLog.Info("AAAAAAAAAAAAAAA3"); FFLog.Warning("AAAAAAAAAAAAAAA4"); FFLog.Error("AAAAAAAAAAAAAAA5"); }
public bool Connect(string args) { if (m_mysql != null) { m_mysql.Close(); m_mysql = null; } bool ret = true; try { string[] strList = args.Split("/");// mysql://127.0.0.1:3306/user/passwd/db if (strList.Length < 5) { return(false); } string[] host_vt = strList[2].Split(":"); string host = host_vt[0]; string port = "3306"; if (host_vt.Length >= 2) { port = host_vt[1]; } string user = strList[3]; string passwd = strList[4]; string db = ""; if (strList.Length >= 6) { db = strList[5]; } string charset = "utf8"; if (strList.Length >= 7) { charset = strList[6]; } string connectionString = string.Format("Database={0};Data Source={1};port={2};User Id={3};Password={4};CharSet={5};", db, host, port, user, passwd, charset); m_mysql = new MySqlConnection(connectionString); m_mysql.Open(); } catch (System.Exception ex) { m_strErr = ex.Message; FFLog.Error("MysqlOps.Connect:" + ex.Message); ret = false; if (m_mysql != null) { m_mysql.Close(); m_mysql = null; } } return(ret); }
public static void Main(string[] args) { CfgTool.Instance().InitCfg(args); string strBrokerListen = CfgTool.Instance().GetCfgVal("BrokerListen", "tcp://127.0.0.1:4321"); if (!FFBroker.Instance().Init(strBrokerListen)) { FFLog.Error("FFBroker open failed!"); return; } int nWorkerIndex = 0; if (FFWorker.Instance().Init(strBrokerListen, nWorkerIndex, listEnableClassNames) == false) { FFLog.Trace("FFWorker open failed!"); return; } string strGateListen = CfgTool.Instance().GetCfgVal("GateListen", "tcp://*:44000"); if (FFGate.Instance().Init(strBrokerListen, strGateListen) == false) { FFLog.Trace("ffGate open failed!"); return; } bool bExit = false; AppDomain.CurrentDomain.ProcessExit += (sender, arg) => { FFLog.Trace("exit!"); bExit = true; }; Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => { e.Cancel = true; FFLog.Trace("exit!!"); bExit = true; }; while (!bExit) { System.Threading.Thread.Sleep(300); } FFLog.Trace("exit!!!"); FFGate.Instance().Cleanup(); FFBroker.Instance().Cleanup(); FFWorker.Instance().Cleanup(); FFNet.Cleanup(); FFLog.Cleanup(); }
public void HandleRecv(IAsyncResult ar) { if (m_nStatus == 0) { FFLog.Trace("scoket: HandleRecv has closed"); return; } var length = 0; try { Socket socket = (Socket)ar.AsyncState; if (socket == null || m_oSocket == null) { return; } length = socket.EndReceive(ar); } catch (Exception ex) { FFLog.Warning("scoket: recv Error1 " + ex.Message); HandleClose(); return; } //FFLog.Trace(string.Format("scoket: recv 1111 {0}", length)); if (length == 0) { FFLog.Warning("HandleRecv: recv end ok file "); HandleClose(); return; } FFNet.GetTaskQueue().Post(() => { try { byte[] message = new byte[length]; Array.Copy(m_oBuffer, 0, message, 0, length); PostMsg(message); //接收下一个消息 if (m_oSocket != null) { m_oSocket.BeginReceive(m_oBuffer, 0, m_oBuffer.Length, SocketFlags.None, new AsyncCallback(HandleRecv), m_oSocket); } } catch (Exception ex) { FFLog.Error("scoket: recv Error2 " + ex.Message); HandleClose(); } }); }
public void HandleMsg(IFFSocket ffsocket, UInt16 cmd, byte[] strMsg) { //FFLog.Trace(string.Format("FFBroker handleMsg....{0}, {1} [{2}]", cmd, strMsg.Length, System.Threading.Thread.CurrentThread.ManagedThreadId.ToString())); try { switch ((FFRPC_CMD)cmd) { case FFRPC_CMD.REGISTER_TO_BROKER_REQ: { RegisterToBrokerReq reqMsg = new RegisterToBrokerReq(); FFNet.DecodeMsg(reqMsg, strMsg); FFLog.Trace(string.Format("FFBroker handleMsg.REGISTER_TO_BROKER_REQ....{0}, {1}", reqMsg.Node_type, reqMsg.Service_name)); if (FFRPC_NODE_TYPE.RPC_NODE == (FFRPC_NODE_TYPE)reqMsg.Node_type) { if (m_brokerData.Service2node_id.ContainsKey(reqMsg.Service_name)) { FFLog.Error(string.Format("FFBroker handleMsg servicename exist....{0}, {1}", reqMsg.Node_type, reqMsg.Service_name)); ffsocket.Close(); return; } Int64 nNodeID = allocNodeId(); m_dictSockets[nNodeID] = ffsocket; m_brokerData.Service2node_id[reqMsg.Service_name] = nNodeID; m_brokerData.Node_id = nNodeID; SyncNodeInfo(m_brokerData, ffsocket); //!广播给所有的子节点 } } break; case FFRPC_CMD.BROKER_ROUTE_MSG: { BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq(); FFNet.DecodeMsg(reqMsg, strMsg); FFLog.Trace(string.Format("FFBroker.BROKER_ROUTE_MSG service={0},func={1} Callback={2}", reqMsg.Dest_service_name, reqMsg.Dest_msg_name, reqMsg.Callback_id)); if (!m_dictSockets.ContainsKey(reqMsg.Dest_node_id)) { return; } IFFSocket destSocket = m_dictSockets[reqMsg.Dest_node_id]; FFNet.SendMsg(destSocket, (UInt16)FFRPC_CMD.BROKER_TO_CLIENT_MSG, reqMsg); } break; default: break; } } catch (Exception ex) { FFLog.Error("FFBroker.Error:" + ex.Message); } }
public object EvalStr(string code) { try { ScriptSource callCode = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.AutoDetect); var result = callCode.Execute(scope); return(result); } catch (Exception e) { FFLog.Error("PyScript.EvalStr:" + code + "->" + e.Message); } return(""); }
public EmptyMsgRet OnRouteLogicMsgReq(RouteLogicMsgReq reqMsg) { int cmd = reqMsg.Cmd; Int64 nSessionID = reqMsg.Session_id; FFLog.Trace(string.Format("worker RouteLogicMsgReq! {0} {1}", cmd, nSessionID)); if (m_dictCmd2Func.ContainsKey(cmd) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}", cmd)); return(RPC_NONE); } if (cmd == (int)Pbmsg.ClientCmdDef.CLogin) { Player playerOld = getPlayerBySessionID(nSessionID); if (playerOld != null) { ClosePlayer(playerOld); if (playerOld.nSessionID == nSessionID) { m_dictRoles.Remove(nSessionID); FFLog.Error(string.Format("worker cmd invalid! {0} {1} login twice", cmd, nSessionID)); return(RPC_NONE); } } else { Player playerNew = new Player() { nSessionID = nSessionID }; m_dictRoles[nSessionID] = playerNew; } } else { if (m_dictRoles.ContainsKey(nSessionID) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}, have not recv login msg", cmd)); return(RPC_NONE); } } Player player = getPlayerBySessionID(nSessionID); m_dictCmd2Func[cmd](player, reqMsg.Body); return(RPC_NONE); }
public bool Open(string strBrokerHost, int nWorkerIndex) { m_nWorkerIndex = nWorkerIndex; m_strWorkerName = string.Format("worker#{0}", m_nWorkerIndex); m_ffrpc = new FFRpc(m_strWorkerName); if (m_ffrpc.Open(strBrokerHost) == false) { FFLog.Error("worker ffrpc open failed!"); return(false); } m_ffrpc.Reg <RouteLogicMsgReq, EmptyMsgRet>(this.OnRouteLogicMsgReq); m_ffrpc.Reg <SessionOfflineReq, EmptyMsgRet>(this.OnSessionOfflineReq); return(true); }
public bool ExeSql(string sql_, QueryCallback cb) { m_strErr = ""; m_nLastAffectRowNum = 0; List <string[]> result = new List <string[]>(); try { MySqlCommand cmd = new MySqlCommand(sql_, m_mysql); if (cb == null) { m_nLastAffectRowNum = cmd.ExecuteNonQuery(); return(true); } MySqlDataReader reader = cmd.ExecuteReader(); //int result =cmd.ExecuteNonQuery();//3.执行插入、删除、更改语句。执行成功返回受影响的数据的行数,返回1可做true判断。执行失败不返回任何数据,报错,下面代码都不执行 m_nLastAffectRowNum = reader.RecordsAffected; int filedCount = reader.FieldCount; string[] colnames = new string[filedCount]; for (int i = 0; i < filedCount; ++i) { colnames[i] = reader.GetName(i); } while (reader.Read())//初始索引是-1,执行读取下一行数据,返回值是bool { string[] row = new string[filedCount]; for (int i = 0; i < filedCount; ++i) { row[i] = reader[i].ToString(); } result.Add(row); } cb(result, colnames, ""); } catch (System.Exception ex) { m_strErr = ex.Message; FFLog.Error("MysqlOps.Connect:" + ex.Message); cb(result, null, m_strErr); return(false); } return(true); }
public object CallPythonFunc(string nameModAndFunc, object[] argsObj) { object ret = null; Int64 nBeginUs = DateTime.Now.Ticks / 10; try { ret = m_h2call(nameModAndFunc, argsObj); } catch (Exception e) { var strArgs = string.Join(",", argsObj); FFLog.Error(string.Format("PyScript.CallPython:{0}({1})exception:{2}", nameModAndFunc, strArgs, e.Message)); } PerfMonitor.Instance().AddPerf(string.Format("py={0}", nameModAndFunc), DateTime.Now.Ticks / 10 - nBeginUs); return(ret); }
public void HandleTimeout(object source, System.Timers.ElapsedEventArgs e) { System.DateTime currentTime = DateTime.Now; Int64 n = ((Int64)currentTime.Ticks) / 10000; m_taskTimer.RemoveAll(data => { if (n >= data.endms) { m_taskTmp.Add(data); if (data.loop) { data.endms = ((Int64)currentTime.Ticks) / 10000 + data.timeoutms; } return(true); } return(false); }); foreach (var data in m_taskTmp) { GetTaskQueue().Post(() => { try { Int64 nBeginUs = DateTime.Now.Ticks / 10; data.task(); if (data.timerName != null && data.timerName != "") { PerfMonitor.Instance().AddPerf("timer=" + data.timerName, DateTime.Now.Ticks / 10 - nBeginUs); } } catch (Exception ex) { FFLog.Error("timer exception:" + ex.Message); return; } }); if (data.loop) { m_taskTimer.Add(data); } } m_taskTmp.Clear(); }
public EmptyMsgRet OnSessionOfflineReq(SessionOfflineReq reqMsg) { Int64 nBeginUs = DateTime.Now.Ticks / 10; Int64 nSessionID = reqMsg.SessionId; FFLog.Trace(string.Format("worker OnSessionOfflineReq! {0}", nSessionID)); int cmd = (int)WorkerDef.OFFLINE_CMD; if (m_dictCmd2Func.ContainsKey(cmd) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}", cmd)); return(RPC_NONE); } byte[] data = {}; m_dictCmd2Func[cmd].cmdHandler(nSessionID, cmd, data); PerfMonitor.Instance().AddPerf("OnOffline", DateTime.Now.Ticks / 10 - nBeginUs); return(RPC_NONE); }
public void SaveLog() { if (m_name2data.Count == 0) { return; } try { string fileName = string.Format("./perf_{0:yyyy-MM-dd}.csv", System.DateTime.Now); bool bExistFile = System.IO.File.Exists(fileName); FileStream fs = new FileStream(fileName, FileMode.Append); StreamWriter sw = new StreamWriter(fs); if (!bExistFile) { sw.WriteLine("time, mod, max, min, per, rps, times"); } string timefmt = string.Format("{0:yyyy-MM-dd HH:mm:ss}", System.DateTime.Now); foreach (var kvp in m_name2data) { string nameMod = kvp.Key; PerfData data = kvp.Value; //! -------------------------- time, mod, max, min, per, rps, times Int64 per = data.total / data.times; Int64 rps = 0; if (per > 0) { rps = 1000 * 1000 / per; } string logdata = string.Format("{0},{1},{2},{3},{4},{5},{6}", timefmt, nameMod, data.max, data.min, per, rps, data.times); sw.WriteLine(logdata); } sw.Flush(); sw.Close(); fs.Close(); } catch (System.Exception ex) { FFLog.Error("PerfMonitor.SaveLog:" + ex.Message); } m_name2data.Clear(); }
public bool Call <MSG_TYPE>(string strServiceName, MSG_TYPE msgData) where MSG_TYPE : Thrift.Protocol.TBase, new() { if (!m_brokerData.Service2nodeId.ContainsKey(strServiceName)) { FFLog.Error(string.Format("ffrpc.Call servervice:{0} not exist", strServiceName)); return(false); } BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq() { CallbackId = 0, Errinfo = "" }; reqMsg.DestNodeId = m_brokerData.Service2nodeId[strServiceName]; reqMsg.DestServiceName = strServiceName; reqMsg.Body = FFNet.EncodeMsg(msgData);//Util.Byte2String( reqMsg.DestMsgName = Type2Name(msgData); SendToDestNode(reqMsg); return(true); }
public bool Listen(string ip, int port) { try{ if (ip == "*" || ip == "") { m_oSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Any, port)); } else { m_oSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), port)); } bRunning = true; m_oSocket.Listen(2); m_oSocket.BeginAccept(new AsyncCallback(HandleAccepted), m_oSocket); } catch (Exception ex) { FFLog.Error("scoket: listen Error " + ex.Message); return(false); } return(true); }
public EmptyMsgRet OnRouteLogicMsgReq(RouteLogicMsgReq reqMsg) { Int64 nBeginUs = DateTime.Now.Ticks / 10; int cmd = reqMsg.Cmd; if ((cmd & 0x4000) != 0) { cmd &= ~(0x4000); } Int64 nSessionID = reqMsg.SessionId; if (m_dictCmd2Func.ContainsKey(cmd) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}", cmd)); return(RPC_NONE); } CmdRegInfo cmdRegInfo = m_dictCmd2Func[cmd]; cmdRegInfo.cmdHandler(nSessionID, reqMsg.Cmd, reqMsg.Body); PerfMonitor.Instance().AddPerf(string.Format("cmd={0}", cmdRegInfo.cmdName), DateTime.Now.Ticks / 10 - nBeginUs); return(RPC_NONE); }
public void HandleRecv(IFFSocket ffsocket, byte[] strData) { if (m_oWSProtocol.HandleRecv(strData)) { if (ffsocket.GetProtocolType().Length == 0) { ffsocket.SetProtocolType("websocket"); } foreach (var eachWaitSend in m_oWSProtocol.GetSendPkg()) { ffsocket.AsyncSend(eachWaitSend, false); } m_oWSProtocol.ClearSendPkg(); foreach (var eachRecvPkg in m_oWSProtocol.GetRecvPkg()) { if (eachRecvPkg.Length == 0) { continue; } UInt16 nCmd = 0; byte[] dataBody = eachRecvPkg; int nHeadEndIndex = -1; if (eachRecvPkg[0] == 'c' || eachRecvPkg[0] == 'C') { ffsocket.SetProtocolType("websocket-text"); for (int i = 0; i < eachRecvPkg.Length; ++i) { if (eachRecvPkg[i] == '\n') { nHeadEndIndex = i; break; } } } if (nHeadEndIndex > 0) { byte[] bytesHead = new byte[nHeadEndIndex]; dataBody = new byte[eachRecvPkg.Length - nHeadEndIndex - 1]; Array.Copy(eachRecvPkg, 0, bytesHead, 0, bytesHead.Length); Array.Copy(eachRecvPkg, nHeadEndIndex + 1, dataBody, 0, dataBody.Length); string[] strHeads = Util.Byte2String(bytesHead).Split(","); string[] strCmds = strHeads[0].Split(":"); if (strCmds.Length == 2 && strCmds[1].Length > 0) { nCmd = Convert.ToUInt16(strCmds[1]); } } else { if (eachRecvPkg.Length < 8) { continue; } size = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(eachRecvPkg, 0)); nCmd = (UInt16)System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(eachRecvPkg, 4)); flag = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(eachRecvPkg, 6)); dataBody = new byte[eachRecvPkg.Length - 8]; Array.Copy(eachRecvPkg, 8, dataBody, 0, dataBody.Length); } //FFLog.Trace(string.Format("cmd={0},data={1}", nCmd, dataBody.Length)); try { m_funcMsgHandler(ffsocket, nCmd, dataBody); } catch (Exception ex) { FFLog.Error("wsscoket.HandleRecv error:" + ex.Message); } } m_oWSProtocol.ClearRecvPkg(); if (m_oWSProtocol.IsClose()) { ffsocket.Close(); } return; } Array.Copy(strData, 0, m_strRecvData, nLeftSize, strData.Length); nLeftSize += strData.Length; //Util.MergeArray(m_strRecvData, strData); int nRead = 0; while (true) { if (nLeftSize < nRead + 8) { Array.Copy(m_strRecvData, nRead, m_strRecvData, 0, nLeftSize - nRead); break; } size = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(m_strRecvData, nRead + 0)); cmd = (UInt16)System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(m_strRecvData, nRead + 4)); flag = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(m_strRecvData, nRead + 6)); //FFLog.Trace(string.Format("HandleRecv cmd:{0},len:{1},recvlen:{2}", cmd, size, m_strRecvData.Length)); if (cmd == 0 || size == 0) { string st = ""; foreach (byte b in m_strRecvData) { st += b.ToString(); } FFLog.Trace(st); m_strRecvData = new byte[0]; string st2 = ""; foreach (byte b in strData) { st2 += b.ToString(); } FFLog.Trace(st2); break; } if (nLeftSize < nRead + 8 + size) { //FFLog.Error("scoket.HandleRecv 111111111111111111"); Array.Copy(m_strRecvData, nRead, m_strRecvData, 0, nLeftSize - nRead); break; } byte[] msgBody = new byte[size]; Array.Copy(m_strRecvData, nRead + 8, msgBody, 0, size); nRead += (8 + size); // if (strData.Length == 8 + size) // { // m_strRecvData = new byte[0]; // } // else{ // FFLog.Trace(string.Format("HandleRecv cmd:{0},len:{1},recvlen:{2},leftData:{3}", cmd, size, m_strRecvData.Length, leftData.Length)); // } try { m_funcMsgHandler(ffsocket, cmd, msgBody); } catch (Exception ex) { FFLog.Error("scoket.HandleRecv error:" + ex.Message); } } nLeftSize -= nRead; }
public void HandleLogin(Int64 nSessionID, Pbmsg.LoginReq reqMsg) { Player playerOld = RoleMgr.Instance().GetPlayerBySessionID(nSessionID); if (playerOld != null) { if (playerOld.nSessionID == nSessionID) { FFLog.Error(string.Format("worker cmd invalid! {0} login twice", nSessionID)); } return; } Player player = new Player() { nSessionID = nSessionID }; RoleMgr.Instance().AddRole(player); player.strName = reqMsg.Name; player.nLevel = 1; Pbmsg.LoginRet retMsg = new Pbmsg.LoginRet() { Id = player.GetID(), Name = reqMsg.Name, Level = player.nLevel, }; player.SendPlayerMsg(Pbmsg.ServerCmdDef.SLogin, retMsg); { Pbmsg.EnterMapRet enterMapRet = player.BuildEnterMsg(); FFWorker.Instance().GateBroadcastMsg((int)Pbmsg.ServerCmdDef.SEnterMap, enterMapRet); player.playerYS = new Player() { nSessionID = player.nSessionID + 100000, strName = player.strName + "的元神", idZhuTi = player.GetID() }; player.playerYS.x = player.x - 1; player.playerYS.y = player.y - 1; player.playerYS.apprID = player.apprID; RoleMgr.Instance().AddRole(player.playerYS); enterMapRet = player.playerYS.BuildEnterMsg(); FFWorker.Instance().GateBroadcastMsg((int)Pbmsg.ServerCmdDef.SEnterMap, enterMapRet); } RoleMgr.Instance().ForeachRole((Role roleOther) => { if (roleOther.GetID() == player.GetID()) { return; } if (roleOther.hp == 0) { return; } Pbmsg.EnterMapRet enterMapRet = roleOther.BuildEnterMsg(); player.SendPlayerMsg(Pbmsg.ServerCmdDef.SEnterMap, enterMapRet); }); }
public void HandleRecv(IFFSocket ffsocket, byte[] strData) { if (m_oWSProtocol.HandleRecv(strData)) { if (ffsocket.GetProtocolType().Length == 0) { ffsocket.SetProtocolType("websocket"); } foreach (var eachWaitSend in m_oWSProtocol.GetSendPkg()) { ffsocket.AsyncSend(eachWaitSend, false); } m_oWSProtocol.ClearSendPkg(); foreach (var eachRecvPkg in m_oWSProtocol.GetRecvPkg()) { int nHeadEndIndex = -1; for (int i = 0; i < eachRecvPkg.Length; ++i) { if (eachRecvPkg[i] == '\n') { nHeadEndIndex = i; break; } } UInt16 nCmd = 0; byte[] dataBody = eachRecvPkg; if (nHeadEndIndex > 0) { byte[] bytesHead = new byte[nHeadEndIndex]; dataBody = new byte[eachRecvPkg.Length - nHeadEndIndex - 1]; Array.Copy(eachRecvPkg, 0, bytesHead, 0, bytesHead.Length); Array.Copy(eachRecvPkg, nHeadEndIndex + 1, dataBody, 0, dataBody.Length); string[] strHeads = Util.Byte2String(bytesHead).Split(","); string[] strCmds = strHeads[0].Split(":"); if (strCmds.Length == 2 && strCmds[1].Length > 0) { nCmd = Convert.ToUInt16(strCmds[1]); } } FFLog.Trace(string.Format("cmd={0},data={1}", nCmd, Util.Byte2String(dataBody))); try { m_funcMsgHandler(ffsocket, nCmd, dataBody); } catch (Exception ex) { FFLog.Error("wsscoket.HandleRecv error:" + ex.Message); } } m_oWSProtocol.ClearRecvPkg(); if (m_oWSProtocol.IsClose()) { ffsocket.Close(); } return; } m_strRecvData = Util.MergeArray(m_strRecvData, strData); while (m_strRecvData.Length >= 8) { size = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt32(m_strRecvData, 0)); cmd = (UInt16)System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(m_strRecvData, 4)); flag = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(m_strRecvData, 6)); FFLog.Trace(string.Format("HandleRecv cmd:{0},len:{1}", cmd, size)); if (m_strRecvData.Length < 8 + size) { break; } byte[] msgBody = new byte[size]; Array.Copy(m_strRecvData, 8, msgBody, 0, size); if (m_strRecvData.Length == 8 + size) { m_strRecvData = new byte[0]; } else { byte[] leftData = new byte[m_strRecvData.Length - (8 + size)]; Array.Copy(m_strRecvData, 8 + size, leftData, 0, size); m_strRecvData = leftData; } try { m_funcMsgHandler(ffsocket, cmd, msgBody); } catch (Exception ex) { FFLog.Error("scoket.HandleRecv error:" + ex.Message); } } }
public void HandleMsg(IFFSocket ffsocket, UInt16 cmd, string strMsg) { //FFLog.Trace(string.Format("ffrpc.FFRpc handleMsg....{0}, {1} [{2}]", cmd, strMsg.Length, System.Threading.Thread.CurrentThread.ManagedThreadId.ToString())); try { switch ((FFRPC_CMD)cmd) { case FFRPC_CMD.REGISTER_TO_BROKER_RET: { FFNet.DecodeMsg(m_brokerData, strMsg); FFLog.Trace(string.Format("ffrpc.handleMsg..REGISTER_TO_BROKER_RET..{0}, {1}", m_brokerData.Node_id, m_brokerData.Register_flag)); if (m_brokerData.Register_flag == 1) { m_nNodeID = m_brokerData.Node_id; //! -1表示注册失败,0表示同步消息,1表示注册成功 } } break; case FFRPC_CMD.BROKER_TO_CLIENT_MSG: { BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq(); FFNet.DecodeMsg(reqMsg, strMsg); FFLog.Trace(string.Format("ffrpc.BROKER_TO_CLIENT_MSG msgname={0}", reqMsg.Dest_msg_name)); if (reqMsg.Err_info.Length > 0) { FFLog.Error(string.Format("FFRpc::handleRpcCallMsg error={0}", reqMsg.Err_info)); if (reqMsg.Callback_id == 0) { return; } } try { if (reqMsg.Dest_service_name.Length > 0) { if (!m_dictFuncs.ContainsKey(reqMsg.Dest_msg_name)) { reqMsg.Err_info = "interface named " + reqMsg.Dest_msg_name + " not found in rpc"; FFLog.Error(string.Format("FFRpc::handleRpcCallMsg error={0}", reqMsg.Err_info)); reqMsg.Dest_node_id = reqMsg.From_node_id; reqMsg.Dest_service_name = ""; SendToDestNode(reqMsg); return; } FFRpcFunc destFunc = m_dictFuncs[reqMsg.Dest_msg_name]; destFunc(reqMsg); } else { if (!m_dictCallBack.ContainsKey(reqMsg.Callback_id)) { return; } FFRpcFunc destFunc = m_dictCallBack[reqMsg.Callback_id]; destFunc(reqMsg); } } catch (Exception ex) { FFLog.Error("ffrpc handleMsg" + ex.Message); } } break; default: break; } } catch (Exception ex) { FFLog.Error("ffprc.Error:" + ex.Message); } }
public EmptyMsgRet OnRouteLogicMsgReq(RouteLogicMsgReq reqMsg) { int cmd = reqMsg.Cmd; Int64 nSessionID = reqMsg.SessionId; //FFLog.Trace(string.Format("worker RouteLogicMsgReq! {0} {1}", cmd, nSessionID)); bool bIsYuanShenMsg = false; if ((cmd & 0x4000) != 0) { cmd &= ~(0x4000); bIsYuanShenMsg = true; } if (m_dictCmd2Func.ContainsKey(cmd) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}", cmd)); return(RPC_NONE); } if (cmd == (int)Pbmsg.ClientCmdDef.CLogin) { Player playerOld = GetPlayerBySessionID(nSessionID); if (playerOld != null) { ClosePlayer(playerOld); if (playerOld.nSessionID == nSessionID) { m_dictRoles.Remove(nSessionID); FFLog.Error(string.Format("worker cmd invalid! {0} {1} login twice", cmd, nSessionID)); return(RPC_NONE); } } else { Player playerNew = new Player() { nSessionID = nSessionID }; m_dictRoles[nSessionID] = playerNew; } } else { if (m_dictRoles.ContainsKey(nSessionID) == false) { FFLog.Error(string.Format("worker cmd invalid! {0}, have not recv login msg", cmd)); return(RPC_NONE); } } Player player = GetPlayerBySessionID(nSessionID); if (bIsYuanShenMsg) { if (null == player.playerYS) { FFLog.Error(string.Format("playerYS invalid", cmd)); return(RPC_NONE); } m_dictCmd2Func[cmd](player.playerYS, reqMsg.Body); } else { m_dictCmd2Func[cmd](player, reqMsg.Body); } return(RPC_NONE); }