Beispiel #1
0
        private void RemoteRequest(int source, string method, NetSprotoType.ClusterClientRequest request, long connectionId, int session)
        {
            int      tag      = NetProtocol.GetInstance().GetTag("RPC");
            RPCParam rpcParam = new RPCParam();

            rpcParam.method = request.method;
            rpcParam.param  = request.param;

            if (m_totalRemoteSession >= Int32.MaxValue)
            {
                m_totalRemoteSession = 0;
            }
            int           remoteSession = ++m_totalRemoteSession;
            List <byte[]> buffers       = m_skynetPacketManager.PackSkynetRequest(request.remoteService, remoteSession, tag, rpcParam.encode());

            SSContext rpcContext = new SSContext();

            rpcContext.LongDict["ConnectionId"]     = connectionId;
            rpcContext.IntegerDict["RemoteSession"] = remoteSession;
            rpcContext.IntegerDict["SourceSession"] = session;
            rpcContext.IntegerDict["Source"]        = source;
            rpcContext.StringDict["Method"]         = method;

            RPCResponseContext rpcResponseCallback = new RPCResponseContext();

            rpcResponseCallback.Callback = RemoteResponseCallback;
            rpcResponseCallback.Context  = rpcContext;
            m_remoteResponseCallbacks.Add(remoteSession, rpcResponseCallback);

            Dictionary <int, WaitForResponseRequest> waitResponseDict = null;
            bool isExist = m_conn2sessions.TryGetValue(connectionId, out waitResponseDict);

            if (!isExist)
            {
                waitResponseDict = new Dictionary <int, WaitForResponseRequest>();
                m_conn2sessions.Add(connectionId, waitResponseDict);
            }

            WaitForResponseRequest waitForResponseRequest = new WaitForResponseRequest();

            waitForResponseRequest.Session = session;
            waitForResponseRequest.Source  = source;
            waitResponseDict.Add(remoteSession, waitForResponseRequest);

            NetworkPacket networkPacket = new NetworkPacket();

            networkPacket.ConnectionId = connectionId;
            networkPacket.TcpObjectId  = m_tcpObjectId;
            networkPacket.Buffers      = buffers;
            networkPacket.Type         = SocketMessageType.DATA;

            NetworkPacketQueue.GetInstance().Push(networkPacket);
        }
Beispiel #2
0
        private ProtocolType JudgeProtocol(NetProtocol netProtocol)
        {
            ProtocolType protocolType = ProtocolType.Tcp;

            switch (netProtocol)
            {
            case NetProtocol.TCP: protocolType = ProtocolType.Tcp;
                break;

            case NetProtocol.UDP: protocolType = ProtocolType.Udp;
                break;
            }
            return(protocolType);
        }
Beispiel #3
0
        private void InitializeNetwork()
        {
            _logger = new TextLogger(rtbLog);
            AppLogger.Initialize(_logger);
            NetLogger.Initialize(_logger);
            NetProtocol.Initialize(new Protocol_12());

            _netClient = new TeamPainterNetClient();

            _netClient.ConnectEvent    += OnClientConnectHandler;
            _netClient.DisconnectEvent += OnClientDisconnectHandler;
            _traffic = new TrafficCounter(100, 0);

            InitializeCommands();
        }
Beispiel #4
0
        static NetProtocol GetProtocol(string protocol, NetProtocol curProtocol)
        {
            switch (protocol.ToLower())
            {
            case "tcp":
                return(NetProtocol.Tcp);

            case "pipe":
                return(NetProtocol.Pipe);

            case "http":
                return(NetProtocol.Http);

            default:
                return(curProtocol);
            }
        }
Beispiel #5
0
        private void InitializeNetwork()
        {
            _logger = new TextLogger(rtbLog);
            AppLogger.Initialize(_logger);
            NetLogger.Initialize(_logger);
            NetProtocol.Initialize(new Protocol_12());

            tbIP.Text   = _config.TCPListenAddress.Address.ToString();
            tbPort.Text = _config.TCPListenAddress.Port.ToString();

            _autorizator = new TPHostAutorizator(_config.MaxClients);
            _worker      = new TPWorkHost(_config.MaxClients);

            _autorizator.Listener.StartEvent += OnStartListener;
            _autorizator.Listener.StopEvent  += OnStopListener;

            _autorizator.DisconnectEvent    += OnDisconnectEventHandler;
            _autorizator.NewConnectionEvent += OnNewTCPConnectionEventHandler;
            _worker.DisconnectEvent         += OnDisconnectEventHandler;
        }
Beispiel #6
0
        private void TransferCallback(SSContext context, string method, byte[] param, RPCError error)
        {
            if (error == RPCError.OK)
            {
                int tag = NetProtocol.GetInstance().GetTag("RPC");
                RPCParam rpcParam = new RPCParam();
                rpcParam.method = method;
                rpcParam.param = Convert.ToBase64String(param);

                int remoteSession = context.IntegerDict["RemoteSession"];
                long connectionId = context.LongDict["ConnectionId"];

                List<byte[]> bufferList = m_skynetPacketManager.PackSkynetResponse(remoteSession, tag, rpcParam.encode());

                NetworkPacket rpcMessage = new NetworkPacket();
                rpcMessage.Type = SocketMessageType.DATA;
                rpcMessage.TcpObjectId = m_tcpObjectId;
                rpcMessage.Buffers = bufferList;
                rpcMessage.ConnectionId = connectionId;

                NetworkPacketQueue.GetInstance().Push(rpcMessage);
            }
            else
            {
                int remoteSession = context.IntegerDict["RemoteSession"];
                long connectionId = context.LongDict["ConnectionId"];

                List<byte[]> bufferList = m_skynetPacketManager.PackErrorResponse(remoteSession, Encoding.ASCII.GetString(param));

                NetworkPacket rpcMessage = new NetworkPacket();
                rpcMessage.Type = SocketMessageType.DATA;
                rpcMessage.TcpObjectId = m_tcpObjectId;
                rpcMessage.Buffers = bufferList;
                rpcMessage.ConnectionId = connectionId;

                NetworkPacketQueue.GetInstance().Push(rpcMessage);

                LoggerHelper.Info(m_serviceAddress, 
                    string.Format("Service:ClusterServer Method:TransferCallback errorCode:{0} errorText:{1}", (int)error, Encoding.ASCII.GetString(param)));
            }
        }
Beispiel #7
0
        private void OnError(Message msg)
        {
            NetProtocol instance = NetProtocol.GetInstance();
            int         tag      = instance.GetTag("Error");

            Error.response sprotoError = (Error.response)instance.Protocol.GenResponse(tag, msg.Data);

            RPCResponseContext responseCallback = null;
            bool isExist = m_responseCallbacks.TryGetValue(msg.RPCSession, out responseCallback);

            if (isExist)
            {
                responseCallback.Callback(responseCallback.Context, msg.Method, Encoding.ASCII.GetBytes(sprotoError.errorText), (RPCError)sprotoError.errorCode);
                m_responseCallbacks.Remove(msg.RPCSession);
            }
            else
            {
                LoggerHelper.Info(m_serviceAddress, string.Format("Service:{0} session:{1} get error:{2}; error text is {3}",
                                                                  m_serviceAddress, msg.RPCSession, sprotoError.errorCode, sprotoError.errorText));
            }
        }
Beispiel #8
0
 public abstract void ReceiveExcute(NetProtocol rev);
Beispiel #9
0
        private Task OnP2pReceive(ISession session, NetDataReader reader)
        {
            NetProtocol protocol = (NetProtocol)reader.ReadUInt16();

            switch (protocol)
            {
            case NetProtocol.P2pInstantiate:
            {
                OnP2pInstantiate(reader);
            }
            break;

            case NetProtocol.P2pDestroy:
            {
                OnP2pDestroy(reader);
            }
            break;

            case NetProtocol.P2pMessage:
            {
                int viewId = reader.ReadInt32();

                var view = _views.Find(viewId);
                if (view == null)
                {
                    return(Task.CompletedTask);
                }

                view.OnNetMessage(reader);
            }
            break;

            case NetProtocol.P2pRequestRecovery:
            {
                OnRequestRecovery(reader);
            }
            break;

            case NetProtocol.P2pResponseRecovery:
            {
                OnResponseRecovery(reader);
            }
            break;

            case NetProtocol.P2pPeriodicSync:
            {
                OnViewPeriodicSyncDeserialize(reader);
            }
            break;

            default:
            {
                int viewId = reader.ReadInt32();

                var view = _views.Find(viewId);
                if (view == null)
                {
                    return(Task.CompletedTask);
                }

                view.OnNetSync(protocol, reader);
            }
            break;
            }

            return(Task.CompletedTask);
        }
Beispiel #10
0
 public byte[] ToArray(NetProtocol protocol)
 {
     byte[] header = protocol.Header2Bytes(Count);
     return(header.Concat(byteQueue.ToArray()).ToArray());
 }
Beispiel #11
0
 //public  NetProtocol netProtocolType;
 public NetParam(string ipAddress, int port, NetProtocol netProtocol)
 {
     this.ipAddress = ipAddress;
     this.port      = port;
     this.protocol  = JudgeProtocol(netProtocol);
 }
Beispiel #12
0
        public static void Run(string[] args)
        {
            ServiceManager manager = new ServiceManager();

            NetProtocol cmdProtocol   = NetProtocol.Tcp;
            string      protocol      = "tcp";
            string      cmd           = "";
            string      operationType = "service";
            string      cmdName       = "";
            string      cmdArg1       = "";

            SetCommands();

            manager.ShowServiceDetails();

            DisplayOperationType(operationType);

            DisplayMenu("menu", "", "");
            //DisplayOperationMessage();
            //operationType = GetOperationType(Console.ReadLine().ToLower(), operationType);

            //if (operationType == "quit")
            //{
            //    return;
            //}
            //Console.WriteLine("Current operation type : {0}.", operationType);


            while (cmd != "quit")
            {
                Console.WriteLine("Enter command :");

                cmd = Console.ReadLine();

                try
                {
                    string[] cmdargs = SplitCmd(cmd);
                    cmdName = GetCommandType(cmdargs[0], cmdName);
                    cmdArg1 = GetCommandType(cmdargs[1], cmdArg1);

                    switch (cmdName.ToLower())
                    {
                    case "menu":
                        DisplayMenu("menu", "", "");
                        break;

                    case "menu-items":
                        DisplayMenu("menu-items", operationType, "");
                        break;

                    case "operation-type":
                        DisplayOperationMessage();
                        operationType = GetOperationType(Console.ReadLine().ToLower(), operationType);
                        Console.WriteLine("Current operation type : {0}.", operationType);
                        break;

                    case "protocol":
                        Console.WriteLine("Choose protocol : tcp , pipe, http");
                        protocol    = EnsureProtocol(Console.ReadLine().ToLower(), protocol);
                        cmdProtocol = GetProtocol(protocol, cmdProtocol);
                        Console.WriteLine("Current protocol : {0}.", protocol);
                        break;

                    case "args":
                        DisplayMenu("args", operationType, cmdArg1);
                        break;

                    case "quit":

                        break;

                    default:
                        switch (operationType)
                        {
                        case "service":

                            switch (cmdName.ToLower())
                            {
                            case "status":
                                manager.DispalyServiceStatus();
                                break;

                            case "details":
                                manager.ShowServiceDetails();
                                break;

                            case "install":
                                manager.DoServiceCommand(ServiceCmd.Install);
                                break;

                            case "uninstall":
                                manager.DoServiceCommand(ServiceCmd.Uninstall);
                                break;

                            case "start":
                                manager.DoServiceCommand(ServiceCmd.Start);
                                break;

                            case "stop":
                                manager.DoServiceCommand(ServiceCmd.Stop);
                                break;

                            case "restart":
                                manager.DoServiceCommand(ServiceCmd.Restart);
                                break;

                            case "paus":
                                manager.DoServiceCommand(ServiceCmd.Pause);
                                break;
                            }
                            //CmdController.DoCommandCache(cmdProtocol,cmdName, cmdArg1, cmdargs[2]);
                            break;
                        }
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: {0}", ex.Message);
                }
                Console.WriteLine();
            }
        }
Beispiel #13
0
        private void Boot(BootServices customBoot)
        {
            // create global instance first
            m_globalMQ     = GlobalMQ.GetInstance();
            m_serviceSlots = ServiceSlots.GetInstance();
            m_netpackQueue = NetworkPacketQueue.GetInstance();
            m_timer        = SSTimer.GetInstance();

            NetProtocol.GetInstance();

            // create logger service second
            Logger_Init loggerInit = new Logger_Init();

            if (m_bootConfig.ContainsKey("Logger"))
            {
                if (Directory.Exists(m_bootConfig["Logger"].ToString()))
                {
                    loggerInit.logger_path = Path.GetFullPath(m_bootConfig["Logger"].ToString());
                }
                else
                {
                    DirectoryInfo di = Directory.CreateDirectory(m_bootConfig["Logger"].ToString());
                    if (di.Exists)
                    {
                        loggerInit.logger_path = Path.GetFullPath(m_bootConfig["Logger"].ToString());
                    }
                    else
                    {
                        loggerInit.logger_path = "../";
                    }
                }
            }
            else
            {
                loggerInit.logger_path = "../";
            }
            SparkServerUtility.NewService("SparkServer.Framework.Service.Logger.LoggerService", "logger", loggerInit.encode());

            m_tcpObjectContainer = new TCPObjectContainer();
            if (m_bootConfig.ContainsKey("ClusterConfig"))
            {
                InitCluster();
            }

            if (m_bootConfig.ContainsKey("Gateway"))
            {
                InitGateway();
            }

            customBoot();

            LoggerHelper.Info(0, "Start SparkServer Server...");

            for (int i = 0; i < m_workerNum; i++)
            {
                Thread thread = new Thread(new ThreadStart(ThreadWorker));
                thread.Start();
            }

            Thread timerThread = new Thread(new ThreadStart(ThreadTimer));

            timerThread.Start();
        }
Beispiel #14
0
 public abstract void ReceiveExcute(NetProtocol rev);