Beispiel #1
0
        public EmptyMsgRet OnSessionOfflineReq(SessionOfflineReq reqMsg)
        {
            Int64 nSessionID = reqMsg.SessionId;

            FFLog.Trace(string.Format("worker OnSessionOfflineReq! {0}", nSessionID));
            if (m_dictRoles.ContainsKey(nSessionID) == false)
            {
                return(RPC_NONE);
            }

            Player player = GetPlayerBySessionID(nSessionID);

            m_dictRoles.Remove(nSessionID);


            Pbmsg.LogoutRet retMsg = new Pbmsg.LogoutRet()
            {
                Id   = player.GetID(),
                Name = player.strName,
            };
            BroadcastPlayerMsg <Pbmsg.LogoutRet>(Pbmsg.ServerCmdDef.SLogout, retMsg);

            if (player.playerYS != null && m_dictRoles.ContainsKey(player.playerYS.nSessionID) != false)
            {
                m_dictRoles.Remove(player.playerYS.nSessionID);
                retMsg = new Pbmsg.LogoutRet()
                {
                    Id   = player.playerYS.GetID(),
                    Name = player.playerYS.strName,
                };
                BroadcastPlayerMsg <Pbmsg.LogoutRet>(Pbmsg.ServerCmdDef.SLogout, retMsg);
            }
            return(RPC_NONE);
        }
Beispiel #2
0
        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);
        }
Beispiel #3
0
        public void HandleBroken(IFFSocket ffsocket)
        {
            Int64  nNodeID        = 0;
            string strServiceName = "";

            foreach (KeyValuePair <Int64, IFFSocket> kvp in m_dictSockets)
            {
                if (kvp.Value == ffsocket)
                {
                    nNodeID = kvp.Key;
                    break;
                }
            }
            if (nNodeID != 0)
            {
                m_dictSockets.Remove(nNodeID);
                foreach (KeyValuePair <string, long> kvp in m_brokerData.Service2node_id)
                {
                    if (kvp.Value == nNodeID)
                    {
                        strServiceName = kvp.Key;
                        break;
                    }
                }
            }
            if (strServiceName.Length > 0)
            {
                m_brokerData.Service2node_id.Remove(strServiceName);
            }
            FFLog.Trace(string.Format("FFBroker HandleBroken....{0}, {1}", nNodeID, strServiceName));
            SyncNodeInfo(m_brokerData, null);
        }
Beispiel #4
0
        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.Service2node_id.ContainsKey(strServiceName))
            {
                FFLog.Trace(string.Format("ffrpc.Call servervice:{0} not exist", strServiceName));
                RET_TYPE retMsg = new RET_TYPE();
                callback(retMsg);
                return(false);
            }
            BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq()
            {
                Callback_id = 0, Err_info = ""
            };

            reqMsg.Dest_node_id      = m_brokerData.Service2node_id[strServiceName];
            reqMsg.Dest_service_name = strServiceName;
            reqMsg.Body          = Util.Byte2String(FFNet.EncodeMsg(msgData));
            reqMsg.Dest_msg_name = Type2Name(msgData);
            reqMsg.Callback_id   = ++m_nIDGenerator;
            m_dictCallBack[reqMsg.Callback_id] = (BrokerRouteMsgReq dataMsg) =>
            {
                RET_TYPE retMsg = new RET_TYPE();
                FFNet.DecodeMsg(retMsg, dataMsg.Body);
                callback(retMsg);
            };
            SendToDestNode(reqMsg);
            return(true);
        }
Beispiel #5
0
        public FFRpc Reg <MSG_TYPE, RET_TYPE>(TUserFunc <MSG_TYPE, RET_TYPE> funcUser)
            where MSG_TYPE : Thrift.Protocol.TBase, new()
            where RET_TYPE : Thrift.Protocol.TBase, new()
        {
            MSG_TYPE tmpData = new MSG_TYPE();
            string   msgname = Type2Name(tmpData);

            FFLog.Trace(string.Format("ffrpc.FFRpc Reg....msgname={0}", msgname));

            m_dictFuncs[msgname] = (BrokerRouteMsgReq reqMsg) =>
            {
                MSG_TYPE msgData = new MSG_TYPE();
                FFNet.DecodeMsg(msgData, reqMsg.Body);
                RET_TYPE retMsg = funcUser(msgData);
                if (reqMsg.Callback_id != 0)
                {
                    reqMsg.Dest_node_id      = reqMsg.From_node_id;
                    reqMsg.Dest_service_name = "";
                    reqMsg.Body = Util.Byte2String(FFNet.EncodeMsg(retMsg));
                    SendToDestNode(reqMsg);
                }
            };

            return(this);
        }
Beispiel #6
0
 public void HandleClose()
 {
     if (m_nStatus == 0)
     {
         return;
     }
     m_nStatus = 0;
     FFNet.GetTaskQueue().Post(() =>
     {
         if (m_oSocket == null)
         {
             return;
         }
         try
         {
             m_oSocket.Close();
             m_oSocket = null;
             m_oBuffSending.Clear();
             m_oSocketCtrl.HandleBroken(this);
         }
         catch (Exception ex)
         {
             FFLog.Trace("scoket: HandleClose Error " + ex.Message);
         }
     });
 }
Beispiel #7
0
 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);
         }
     }
 }
Beispiel #8
0
        public void HandleAccepted(IAsyncResult ar)
        {
            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.Trace(string.Format("scoket: handleAccepted ip:{0}", ffsocket.GetIP()));
                }
            }
            catch (Exception ex)
            {
                FFLog.Trace("scoket: handleAccepted Error " + ex.Message);
            }

            if (bRunning)
            {
                m_oSocket.BeginAccept(new AsyncCallback(HandleAccepted), m_oSocket);
            }
        }
Beispiel #9
0
 private void handleSendEnd(IAsyncResult ar)
 {
     try
     {
         var socket = ar.AsyncState as Socket;
         socket.EndSend(ar);
     }
     catch (SocketException ex)
     {
         FFLog.Trace("scoket: send Error " + ex.Message);
         HandleClose();
         return;
     }
     FFNet.GetTaskQueue().Post(() =>
     {
         if (m_oBuffSending.Count > 0)
         {
             m_oBuffSending.RemoveAt(0);
         }
         try
         {
             if (m_oBuffSending.Count > 0 && m_oSocket != null)
             {
                 byte[] data = m_oBuffSending[0];
                 m_oSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(handleSendEnd), m_oSocket);
             }
         }
         catch (SocketException ex)
         {
             FFLog.Trace("scoket: send Error " + ex.Message);
             HandleClose();
         }
     });
 }
Beispiel #10
0
        public void HandleLogout(Int64 nSessionID)
        {
            FFLog.Trace(string.Format("PlayerHandler.HandleLogout {0}", nSessionID));
            Player player = RoleMgr.Instance().GetPlayerBySessionID(nSessionID);

            if (player == null)
            {
                return;
            }
            RoleMgr.Instance().RemoveRole(nSessionID);

            Pbmsg.LogoutRet retMsg = new Pbmsg.LogoutRet()
            {
                Id   = player.GetID(),
                Name = player.strName,
            };
            FFWorker.Instance().GateBroadcastMsg((int)Pbmsg.ServerCmdDef.SLogout, retMsg);

            if (player.playerYS != null && RoleMgr.Instance().GetPlayerBySessionID(player.playerYS.nSessionID) != null)
            {
                RoleMgr.Instance().RemoveRole(player.playerYS.nSessionID);;
                retMsg = new Pbmsg.LogoutRet()
                {
                    Id   = player.playerYS.GetID(),
                    Name = player.playerYS.strName,
                };
                FFWorker.Instance().GateBroadcastMsg((int)Pbmsg.ServerCmdDef.SLogout, retMsg);
            }
            return;
        }
Beispiel #11
0
        public static void Main(string[] args)
        {
            string   host     = "tcp://127.0.0.1:43210";
            FFBroker ffbroker = new FFBroker();

            ffbroker.Open(host);

            string strServiceName = "worker#0";
            FFRpc  ffrpc          = new FFRpc(strServiceName);

            if (ffrpc.Open(host) == false)
            {
                FFLog.Trace("ffrpc open failed!");
            }
            ffrpc.Reg((SessionEnterWorkerReq req) =>
            {
                FFLog.Trace(string.Format("ffrpc SessionEnterWorkerReq £¡£¡£¡FromGate={0}", req.From_gate));
                return(req);
            });
            Console.ReadKey();
            ffrpc.GetTaskQueue().Post(() =>
            {
                SessionEnterWorkerReq reqMsg = new SessionEnterWorkerReq()
                {
                    From_gate = "gate#0"
                };
                WorkerCallMsgReq reqWorkerCall = new WorkerCallMsgReq();
                //ffrpc.Call(strServiceName, reqMsg);
                reqMsg.From_gate = "gate#1";
                ffrpc.Call(strServiceName, reqWorkerCall, (SessionEnterWorkerReq retMsg) =>
                {
                    FFLog.Trace(string.Format("ffrpc SessionEnterWorkerReq return£¡£¡£¡FromGate={0}", retMsg.From_gate));
                });
            });

            //FFNet.Timerout(1000, Theout);
            //FFNet.Timerout(2000, Theout);
            FFNet.Timerout(100000, () =>
            {
                FFLog.Debug("AAAAAAAAAAAAAAA1");
                ffrpc.Close();
            });
            FFLog.Trace(string.Format("main! {0}", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()));

            AppDomain.CurrentDomain.ProcessExit += (sender, arg) =>
            {
                FFLog.Trace("exist!!");
            };
            Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => {
                e.Cancel = true;
                FFLog.Trace("exist3!!");

                FFNet.Cleanup();
                FFLog.Cleanup();
            };
            Console.ReadKey();
            FFLog.Trace("exist!!");
            FFNet.Cleanup();
            FFLog.Cleanup();
        }
Beispiel #12
0
 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");
 }
Beispiel #13
0
 public void Close()
 {
     try {
         m_oSocket.Close();
     }
     catch (Exception ex)
     {
         FFLog.Trace("scoket: close Error " + ex.Message);
     }
 }
Beispiel #14
0
        public EmptyMsgRet OnSessionEnterWorkerReq(SessionEnterWorkerReq reqMsg)
        {
            Int64 nBeginUs   = DateTime.Now.Ticks / 10;
            Int64 nSessionID = reqMsg.SessionId;

            FFLog.Trace(string.Format("worker OnSessionEnterWorkerReq session={0}", nSessionID));

            this.funcSessionOnEnterWorker?.Invoke(nSessionID, reqMsg.FromWorker, reqMsg.ExtraData);
            PerfMonitor.Instance().AddPerf("OnEnterWorker", DateTime.Now.Ticks / 10 - nBeginUs);
            return(RPC_NONE);
        }
Beispiel #15
0
 public bool Connect(string ip, int port)
 {
     try{
         m_oSocket.Connect(ip, port);
     }
     catch (Exception ex)
     {
         FFLog.Trace("scoket: connect Error " + ex.Message);
         return(false);
     }
     AsyncRecv();
     return(true);
 }
Beispiel #16
0
        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();
        }
Beispiel #17
0
        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();
                }
            });
        }
Beispiel #18
0
        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);
            }
        }
Beispiel #19
0
        public bool Open(string strBrokerCfg)
        {
            if (strBrokerCfg.Length > 0)
            {
                m_strBrokerHost = strBrokerCfg;
            }

            FFLog.Trace(string.Format("ffrpc open....{0} begin", m_strBrokerHost));
            if (!ConnectToBroker())
            {
                return(false);
            }
            return(true);
        }
Beispiel #20
0
        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);
        }
Beispiel #21
0
        public static void SendMsg(IFFSocket ffsocket, UInt16 cmdSrc, byte[] strData)
        {
            int len = strData.Length;

            len = System.Net.IPAddress.HostToNetworkOrder(len);
            UInt16 cmd = (UInt16)System.Net.IPAddress.HostToNetworkOrder((Int16)cmdSrc);

            byte[] lenArray = BitConverter.GetBytes(len);
            byte[] cmdArray = BitConverter.GetBytes(cmd);
            byte[] resArray = new byte[2] {
                0, 0
            };
            byte[][] p        = { lenArray, cmdArray, resArray, strData };
            byte[]   sendData = Util.MergeArray(p);
            ffsocket.AsyncSend(sendData);
            FFLog.Trace(string.Format("SendMsg cmd:{0},len:{1},len2:{2}", cmdSrc, strData.Length, sendData.Length));
        }
Beispiel #22
0
        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);
        }
Beispiel #23
0
        public bool Open(string strBrokerCfg)
        {
            if (strBrokerCfg.Length > 0)
            {
                m_strListenHost = strBrokerCfg;
            }

            m_acceptor = FFNet.Listen(m_strListenHost, new SocketMsgHandler(HandleMsg), new SocketBrokenHandler(HandleBroken));
            if (m_acceptor != null)
            {
                FFLog.Trace(string.Format("FFBroker open....{0} ok", m_strListenHost));
            }
            else
            {
                FFLog.Trace(string.Format("FFBroker open....{0} failed", m_strListenHost));
            }
            return(true);
        }
Beispiel #24
0
        public static string InitClassByNames(string[] names)
        {
            string nspace = "ff";

            var q = from t in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass && t.Namespace == nspace
                    select t;

            foreach (string name in names)
            {
                foreach (var t in q.ToList())
                {
                    if (t.Name != name)
                    {
                        continue;
                    }

                    object[] paraNone = new object[] {};
                    System.Reflection.MethodInfo method = t.GetMethod("Instance");
                    if (method != null)
                    {
                        //Console.WriteLine(t.Name + ":" + method);
                        var ret = method.Invoke(null, paraNone);
                        System.Reflection.MethodInfo initMethod = t.GetMethod("Init");
                        if (initMethod != null)
                        {
                            object retB = initMethod.Invoke(ret, paraNone);
                            if (retB != null && retB is bool)
                            {
                                bool b = (bool)retB;
                                FFLog.Trace(string.Format("{0} init {1}", t.Name, b?"ok":"failed"));
                                if (!b)
                                {
                                    return(t.Name);
                                }
                            }
                        }
                    }
                    break;
                }
            }
            return("");
        }
Beispiel #25
0
        public void HandleAccepted(IAsyncResult ar)
        {
            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_funcRecv, m_funcBroken, client);
                    ffsocket.AsyncRecv();
                    m_oSocket.BeginAccept(new AsyncCallback(HandleAccepted), m_oSocket);
                }
            }
            catch (Exception ex)
            {
                FFLog.Trace("scoket: handleAccepted Error " + ex.Message);
            }
        }
Beispiel #26
0
        public bool Call <MSG_TYPE>(string strServiceName, MSG_TYPE msgData)
            where MSG_TYPE : Thrift.Protocol.TBase, new()
        {
            if (!m_brokerData.Service2node_id.ContainsKey(strServiceName))
            {
                FFLog.Trace(string.Format("ffrpc.Call servervice:{0} not exist", strServiceName));
                return(false);
            }
            BrokerRouteMsgReq reqMsg = new BrokerRouteMsgReq()
            {
                Callback_id = 0, Err_info = ""
            };

            reqMsg.Dest_node_id      = m_brokerData.Service2node_id[strServiceName];
            reqMsg.Dest_service_name = strServiceName;
            reqMsg.Body          = Util.Byte2String(FFNet.EncodeMsg(msgData));
            reqMsg.Dest_msg_name = Type2Name(msgData);
            SendToDestNode(reqMsg);
            return(true);
        }
Beispiel #27
0
 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));
         }
         m_oSocket.Listen(2);
         m_oSocket.BeginAccept(new AsyncCallback(HandleAccepted), m_oSocket);
     }
     catch (Exception ex)
     {
         FFLog.Trace("scoket: listen Error " + ex.Message);
         return(false);
     }
     return(true);
 }
Beispiel #28
0
        private void RunAllTask()
        {
            List <FFTask> taskToRun = new List <FFTask>();

            while (m_running)
            {
                m_mutex.WaitOne();
                while (m_running && m_taskList.Count == 0)
                {
                    m_mutex.ReleaseMutex();
                    m_event.WaitOne(100);
                    m_mutex.WaitOne();
                }
                foreach (FFTask task in m_taskList)
                {
                    taskToRun.Add(task);
                }
                m_taskList.Clear();
                m_mutex.ReleaseMutex();
                foreach (FFTask task in taskToRun)
                {
                    try
                    {
                        task();
                    }
                    catch (System.Exception ex)
                    {
                        FFLog.Trace("void RunAllTask exception:" + ex.Message);
                        continue;
                    }
                    finally
                    {
                    }
                }
                taskToRun.Clear();
            }
        }
Beispiel #29
0
        //!切换worker
        public EmptyMsgRet ChangeSessionLogic(GateChangeLogicNodeReq reqMsg)
        {
            FFLog.Trace(string.Format("FFGate ChangeSessionLogic....sessionid={0}", reqMsg.SessionId));
            if (m_dictClients.ContainsKey(reqMsg.SessionId) == false)
            {
                return(m_msgEmpty);
            }
            ClientInfo            cinfo    = m_dictClients[reqMsg.SessionId];
            SessionEnterWorkerReq msgEnter = new SessionEnterWorkerReq()
            {
            };

            msgEnter.FromWorker  = cinfo.strAllocWorker;
            cinfo.strAllocWorker = reqMsg.AllocWorker;

            msgEnter.SessionId = reqMsg.SessionId;
            msgEnter.FromGate  = m_strGateName;
            msgEnter.SessionIp = cinfo.sockObj.GetIP();

            msgEnter.ToWorker  = reqMsg.AllocWorker;
            msgEnter.ExtraData = reqMsg.ExtraData;
            m_ffrpc.Call(reqMsg.AllocWorker, msgEnter);
            return(m_msgEmpty);
        }
Beispiel #30
0
        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;
        }