Exemplo n.º 1
0
        private void SendPendingCommand()
        {
            var command = _commandsToSend.Count > 0 ? _commandsToSend.Dequeue() : new NoCommand();

            //action.NetworkAverage = Network.GetLastPing (Network.connections[0/*host player*/]);
            command.NetworkAverage = LockStepTurnId > FirstLockStepTurnID + 1 ? _confirmedCommands.GetPriorTime() : _initialLockStepTurnLength;

            command.RuntimeAverage = Convert.ToInt32(_currentGameFrameRuntime);
            //clear the current runtime average
            _currentGameFrameRuntime = 0;

            //add action to our own list of actions to process TODO: _myPlayerId
            _pendingCommnads.AddCommand(command, _myPlayerId, LockStepTurnId, LockStepTurnId);

            //start the confirmed action timer for network average
            _confirmedCommands.StartTimer();
            //confirm our own action
            _confirmedCommands.ConfirmCommand(_myPlayerId, LockStepTurnId, LockStepTurnId);

            //TODO: tell other
            //send action to all other players
//            nv.RPC("RecieveAction", RPCMode.Others, LockStepTurnId, _myPlayerId, BinarySerialization.SerializeObjectToByteArray(action));

            SkynetLogger.Info(Channel.LockStep, "Sent " + (command.GetType().Name) + " action for turn " + LockStepTurnId);
        }
Exemplo n.º 2
0
        private void Message(object sender, MessageEventArgs e)
        {
            switch (e.Opcode)
            {
            case Opcode.Text:
                _protocol.ProcessMessage(e.Data);
                break;

            case Opcode.Binary:
                _protocol.ProcessMessage(e.RawData);
                break;

            case Opcode.Close:
                SkynetLogger.Error(Channel.NetDevice, "[OnMessage] OpCode Closed");
                break;

            case Opcode.Cont:
                break;

            case Opcode.Ping:
                break;

            case Opcode.Pong:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 3
0
    public void Start()
    {
        SkynetLogger.Error(Channel.NetDevice, "++++++Skynet Client Start++++");

        _login = new TestLoginTcp(Protocol);
        _login.Run(ProcessLoginResp);
    }
Exemplo n.º 4
0
        public void ProcessMessage(SpRpcResult msg)
        {
            if (msg.ud != 0)
            {
                SkynetLogger.Error(Channel.NetDevice, "resp error code is: " + msg.ud);
                _eventManager.RemoveCallBack(msg.Session);
                return;
            }

            switch (msg.Op)
            {
            case SpRpcOp.Request:
                SkynetLogger.Info(Channel.NetDevice, "Recv Request : " + msg.Protocol.Name + ", session : " + msg.Session);
                Utils.Util.DumpObject(msg.Data);

                _eventManager.InvokeOnEvent(msg.Protocol.Name, msg.Data);
                break;

            case SpRpcOp.Response:
                if (msg.Protocol.Name != "heartbeat")
                {
                    SkynetLogger.Info(Channel.NetDevice, "Recv Response : " + msg.Protocol.Name + ", session : " + msg.Session);
                    Utils.Util.DumpObject(msg.Data);
                }

                _eventManager.InvokeCallBack(msg.Session, msg.Data);
                break;

            case SpRpcOp.Unknown:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 5
0
    private void OnDestroy()
    {
        if (_login != null)
        {
            _login.DisConnect();
            _login = null;
        }

        if (_gateTcp != null)
        {
            _gateTcp.DisConnect();
            _gateTcp = null;
        }

        if (_gateWs != null)
        {
            _gateWs.DisConnect();
            _gateWs = null;
        }

        if (_gateUdp != null)
        {
            _gateUdp.DisConnect();
            _gateUdp = null;
        }

        SkynetLogger.Error(Channel.NetDevice, "++++++Skynet Client Destroy++++");
    }
Exemplo n.º 6
0
        private void NetWorkStateCallBack(NetWorkState state)
        {
            SkynetLogger.Info(Channel.NetDevice, "Gate WS NetWorkStateCallBack:" + state);
            if (state == NetWorkState.Connected)
            {
                //TODO:发送 与 gate 握手消息成功后 开启 心跳操作
                SpObject handshakeRequset = new SpObject();
                handshakeRequset.Insert("uid", _req.uid);
                handshakeRequset.Insert("secret", _req.secret);
                handshakeRequset.Insert("subid", _req.subid);

                _client.Request("handshake", handshakeRequset, (SpObject obj) =>
                {
                    {
                        int role = obj["role"].AsInt();
                        if (role == 0)
                        {
                            SpObject bornRequest = new SpObject();
                            bornRequest.Insert("name", "helloworld");
                            bornRequest.Insert("head", "1111111111");
                            bornRequest.Insert("job", "1");
                            _client.Request("born", bornRequest,
                                            (SpObject bornObj) => { SkynetLogger.Info(Channel.NetDevice, "born resp is ok"); });
                        }
                        else
                        {
                            SkynetLogger.Info(Channel.NetDevice, "is has role");
                        }
                    }
                });
            }
        }
Exemplo n.º 7
0
        void VerifySucess(SpObject sp)
        {
            SkynetLogger.Info(Channel.NetDevice, "is OnVerifySucess");

            _client.StartHeartBeatService();
            //TODO: 请求各模块信息
        }
Exemplo n.º 8
0
        //private static void ConfigureCertificateValidatation(
        //    bool validateCertificates,
        //    out System.Net.SecurityProtocolType protocolType,
        //    out RemoteCertificateValidationCallback prevValidator)
        //   {
        //       prevValidator = null;
        //       protocolType = (System.Net.SecurityProtocolType)0;

        //       if (!validateCertificates)
        //       {
        //           protocolType = System.Net.ServicePointManager.SecurityProtocol;
        //           System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
        //           prevValidator = System.Net.ServicePointManager.ServerCertificateValidationCallback;
        //           System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
        //       }
        //   }

        public static void DoLoginReqAction(AuthPackageReq cmd, LoginAuthRespCallBack cb)
        {
            respcb = cb;
            LoginwReqPack req = new LoginwReqPack();

            req.parms = JsonMapper.ToJson(cmd);
            string jsonStr = JsonMapper.ToJson(req);

            IHttpContent content = new StringContent(jsonStr, System.Text.Encoding.UTF8, "application/json");

            client.Post(new Uri(url), content, HttpCompletionOption.AllResponseContent, r =>
            {
                if (r.IsSuccessStatusCode)
                {
                    var respStr = r.ReadAsString();
                    try
                    {
                        AuthPackageResp resp = JsonMapper.ToObject <AuthPackageResp>(respStr);
                        respcb(resp);
                    }
                    catch (Exception e)
                    {
                        SkynetLogger.Error(Channel.NetDevice, "Json Deserialize err:" + e.Message.ToString());
                    }
                }
            });
        }
Exemplo n.º 9
0
    private void OnGUI()
    {
        EditorGUI.BeginChangeCheck();

        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Clear all"))
        {
            loggerChannels = 0;
        }
        if (GUILayout.Button("Select all"))
        {
            loggerChannels = SkynetLogger.kAllChannels;
        }

        EditorGUILayout.EndHorizontal();

        GUILayout.Label("Click to toggle logging channels", EditorStyles.boldLabel);

        foreach (Channel channel in System.Enum.GetValues(typeof(Channel)))
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Toggle((loggerChannels & channel) == channel, "", GUILayout.ExpandWidth(false));
            if (GUILayout.Button(channel.ToString()))
            {
                loggerChannels ^= channel;
            }
            EditorGUILayout.EndHorizontal();
        }

        // If the game is playing then update it live when changes are made
        if (EditorApplication.isPlaying && EditorGUI.EndChangeCheck())
        {
            SkynetLogger.SetChannels(loggerChannels);
        }
    }
Exemplo n.º 10
0
        public void ConfirmCommand(int confirmingPlayerId, int currentLockStepTurn, int confirmedCommandLockStepTurn)
        {
            if (confirmedCommandLockStepTurn == currentLockStepTurn)
            {
                //if current turn, add to the current Turn Confirmation
                _confirmedCurrent[confirmingPlayerId] = true;
                _confirmedCurrentCount++;

                //if we recieved the last confirmation, stop timer
                //this gives us the length of the longest roundtrip message
                if (_confirmedCurrentCount == _lockStepManager.NumberOfPlayers)
                {
                    _currentSw.Stop();
                }
            }
            else if (confirmedCommandLockStepTurn == (currentLockStepTurn - 1))
            {
                //if confirmation for prior turn, add to the prior turn confirmation
                _confirmedPrior[confirmingPlayerId] = true;
                _confirmedPriorCount++;
                //if we recieved the last confirmation, stop timer
                //this gives us the length of the longest roundtrip message
                if (_confirmedPriorCount == _lockStepManager.NumberOfPlayers)
                {
                    _priorSw.Stop();
                }
            }
            else
            {
                SkynetLogger.Error(Channel.LockStep, "Unexpected lockstepID Confirmed : " + confirmedCommandLockStepTurn + " from player: " + confirmingPlayerId);
            }
        }
Exemplo n.º 11
0
        public void ProcessMessage(SpRpcResult msg)
        {
            if (msg.ud != 0)
            {
                SkynetLogger.Error(Channel.Udp, "udp client resp error code is: " + msg.ud);
                return;
            }

            switch (msg.Op)
            {
            case SpRpcOp.Request:
                SkynetLogger.Info(Channel.Udp, "udp client recv Request : " + msg.Protocol.Name + ", session : " + msg.Session);
                Utils.Util.DumpObject(msg.Data);
                break;

            case SpRpcOp.Response:
                if (msg.Protocol.Name != "heartbeat")
                {
                    SkynetLogger.Info(Channel.Udp, "udp client recv Response : " + msg.Protocol.Name + ", session : " + msg.Session);
                    Utils.Util.DumpObject(msg.Data);
                }
                break;

            case SpRpcOp.Unknown:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 12
0
        private void EndReceive(IAsyncResult asr)
        {
            if (_transportState == TransportState.Closed)
            {
                return;
            }
            var state = (StateObject)asr.AsyncState;

            try
            {
                var length = _socket.EndReceive(asr);
                if (length > 0)
                {
                    ProcessBytes(state.buffer, 0, length);
                    Receive();
                }
                else
                {
                    SkynetLogger.Error(Channel.NetDevice, "没有接收到任何数据 远端连接断开");

                    onDisconnect?.Invoke();
                }
            }
            catch (SocketException e)
            {
                onDisconnect?.Invoke();

                SkynetLogger.Error(Channel.NetDevice, "Socket Exception连接断开:" + e.Message);
            }
        }
Exemplo n.º 13
0
 public void RawSend(byte[] data, int length)
 {
     if (length >= 512)
     {
         SkynetLogger.Error(Channel.Udp, "Send Data overload 1 MTU");
     }
     _udpClient.SendAsync(data, length);
 }
Exemplo n.º 14
0
        public void Connect(BattleSession battleSession)
        {
            Protocol.Init(battleSession.session, battleSession.secret);

            _connector = new Transporter(this);

            var endpoint = battleSession.host + ":" + battleSession.port;

            SkynetLogger.Info(Channel.Udp, "Udp Client URL " + endpoint);
            _connector.Connect(battleSession.host, battleSession.port);
        }
Exemplo n.º 15
0
        public SpStream Pack(string proto, int session, SpObject args)
        {
            _stream.Reset();

            if (proto != "heartbeat")
            {
                SkynetLogger.Info(Channel.NetDevice, "Send Request : " + proto + ", session : " + session);;
            }

            _rpc.Request(proto, args, session, _stream);
            return(_stream);
        }
Exemplo n.º 16
0
        public static SpStream Pack(string proto, int session, SpObject args)
        {
            _stream.Reset();

            SkynetLogger.Info(Channel.Udp, "Send Request : " + proto + ", session : " + session);

            _stream.Write(_session);
            _stream.Write(_secret);

            _rpc.Request(proto, args, session, _stream);

            return(_stream);
        }
Exemplo n.º 17
0
        private void Close(object sender, CloseEventArgs e)
        {
            var code = (CloseStatusCode)e.Code;

            if (code != CloseStatusCode.NoStatus && code != CloseStatusCode.Normal)
            {
                SkynetLogger.Error(Channel.NetDevice, "[ERROR] " + e.Reason + " " + e.Code);
            }
            else
            {
                SkynetLogger.Error(Channel.NetDevice, "[INFO] Closed");
            }
            NetWorkChanged(NetWorkState.Error);
        }
Exemplo n.º 18
0
        private void SendHeartBeat(object source, ElapsedEventArgs e)
        {
            var span = DateTime.Now - _lastTime;

            _timeout = (int)span.TotalMilliseconds;
            if (_timeout > _interval * 2)
            {
                SkynetLogger.Info(Channel.NetDevice, "timeout disconnect");
                _client.Disconnect();
            }
            else
            {
                _client.Request("heartbeat", (SpObject obj) => { ResetTimeout(); });
            }
        }
Exemplo n.º 19
0
        private void Connect(IAsyncResult asr)
        {
            try
            {
                _socket.EndConnect(asr);
                _protocol = new Protocol(this, this._socket);
                NetWorkChanged(NetWorkState.Connected);
            }
            catch (Exception e)
            {
                SkynetLogger.Error(Channel.NetDevice, $"连接服务器异步结果错误:{e.Message.ToString()}");

                NetWorkChanged(NetWorkState.Error);
                Dispose();
            }
        }
Exemplo n.º 20
0
        public void Connect(string host, int port)
        {
            var url = "ws://" + host + ":" + port.ToString();

            SkynetLogger.Info(Channel.NetDevice, "Ws Client URL " + url);
            _socket            = new WebSocket(url);
            _socket.OnOpen    += Open;
            _socket.OnClose   += Close;
            _socket.OnMessage += Message;
            _socket.OnError   += Error;

            if (!_socket.IsAlive)
            {
                _socket.ConnectAsync();
            }
        }
Exemplo n.º 21
0
        //public static void ConfigureCertificate()
        //{
        //    System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
        //    System.Net.ServicePointManager.ServerCertificateValidationCallback = null;

        //    RemoteCertificateValidationCallback prevValidator;
        //    System.Net.SecurityProtocolType protocolType;

        //    ConfigureCertificateValidatation(false, out protocolType, out prevValidator);
        //}

        public static void Test()
        {
            client.Get(new Uri("https://api.weixin.qq.com/sns/userinfo"), HttpCompletionOption.AllResponseContent, (r) =>
            {
                if (r.IsSuccessStatusCode)
                {
                    string str = r.ReadAsString();
                    SkynetLogger.Info(Channel.NetDevice, "responstr:" + str);
                    SkynetLogger.Info(Channel.NetDevice, "+++++Test responstr+++++++++" + str);
                }
                else
                {
                    SkynetLogger.Info(Channel.NetDevice, "statuscode:" + r.StatusCode.ToString());
                    SkynetLogger.Info(Channel.NetDevice, "+++++Test statuscode+++++++++" + r.StatusCode.ToString());
                }
            });
        }
Exemplo n.º 22
0
        private void NetWorkStateCallBack(NetWorkState state)
        {
            SkynetLogger.Info(Channel.Udp, "Gate Udp NetWorkStateCallBack:" + state);
            if (state != NetWorkState.Connected)
            {
                return;
            }

            //TODO:发送 与 gate 握手消息成功后 开启 心跳操作
            var handshakeRequset = new SpObject();

            handshakeRequset.Insert("uid", "ddddddddddd");
            _client.Request("handshake", handshakeRequset, (SpObject obj) =>
            {
                SkynetLogger.Info(Channel.Udp, "udp handshake resp");
            });
        }
Exemplo n.º 23
0
        public void PrepGameStart()
        {
            SkynetLogger.Info(Channel.LockStep, "----------PrepGameStart------");

            LockStepTurnId     = FirstLockStepTurnID;
            NumberOfPlayers    = _networkManager.NumberOfPlayers;
            _pendingCommnads   = new PendingCommnads();
            _confirmedCommands = new ConfirmedCommands();
            _commandsToSend    = new Queue <Command>();

            _gameTurnSw = new Stopwatch();
            _currentGameFrameRuntime = 0;
            _networkAverage          = new RollingAverage(NumberOfPlayers, _initialLockStepTurnLength);
            _runtimeAverage          = new RollingAverage(NumberOfPlayers, _initialGameFrameTurnLength);

            InitGameStart();
        }
Exemplo n.º 24
0
 public void AddCommand(Command cmd, int playerId, int currentLockStepTurn, int cmdsLockStepTurn)
 {
     //add cmd for processing later
     if (cmdsLockStepTurn == currentLockStepTurn + 1)
     {
         //if action is for next turn, add for processing 3 turns away
         if (_nextNextNextCommands[playerId] != null)
         {
             //TODO: Error Handling
             SkynetLogger.Error(Channel.LockStep, "Recieved multiple actions for player " + playerId + " for turn " + cmdsLockStepTurn);
         }
         _nextNextNextCommands[playerId] = cmd;
         _nextNextNextCommandsCount++;
     }
     else if (cmdsLockStepTurn == currentLockStepTurn)
     {
         //if recieved action during our current turn
         //add for processing 2 turns away
         if (_nextNextCommands[playerId] != null)
         {
             //TODO: Error Handling
             SkynetLogger.Error(Channel.LockStep, "Recieved multiple actions for player " + playerId + " for turn " + cmdsLockStepTurn);
         }
         _nextNextCommands[playerId] = cmd;
         _nextNextCommandsCount++;
     }
     else if (cmdsLockStepTurn == currentLockStepTurn - 1)
     {
         //if recieved action for last turn
         //add for processing 1 turn away
         if (_nextCommands[playerId] != null)
         {
             //TODO: Error Handling
             SkynetLogger.Error(Channel.LockStep, "Recieved multiple actions for player " + playerId + " for turn " + cmdsLockStepTurn);
         }
         _nextCommands[playerId] = cmd;
         _nextCommandsCount++;
     }
     else
     {
         //TODO: Error Handling
         SkynetLogger.Error(Channel.LockStep, " Unexpected lockstepID recieved : " + cmdsLockStepTurn);
     }
 }
Exemplo n.º 25
0
        public void Connect(string host, int port)
        {
            NetWorkChanged(NetWorkState.Connecting);
            IPAddress ipAddress = null;

            try
            {
                var addresses = Dns.GetHostEntry(host).AddressList;
                foreach (var item in addresses)
                {
                    if (item.AddressFamily != AddressFamily.InterNetwork)
                    {
                        continue;
                    }
                    ipAddress = item;
                    break;
                }
            }
            catch (Exception)
            {
                NetWorkChanged(NetWorkState.Error);
                return;
            }

            if (ipAddress == null)
            {
                throw new Exception("can not parse host : " + host);
            }

            try
            {
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var ie = new IPEndPoint(ipAddress, port);

                _socket.BeginConnect(ie, Connect, null);
            }
            catch (Exception e)
            {
                SkynetLogger.Error(Channel.NetDevice, $"连接服务器失败:{e.Message.ToString()}");
            }
        }
Exemplo n.º 26
0
        private bool NextTurn()
        {
            if (_confirmedCommands.ReadyNextTurn())
            {
                if (_pendingCommnads.ReadyForNextTurn())
                {
                    //increment the turn ID
                    LockStepTurnId++;
                    //move the confirmed actions to next turn
                    _confirmedCommands.NextTurn();
                    //move the pending actions to this turn
                    _pendingCommnads.NextTurn();

                    return(true);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("Have not recieved player(s) actions: ");
                    foreach (int i in _pendingCommnads.WhosNotReady())
                    {
                        sb.Append(i + ", ");
                    }
                    SkynetLogger.Info(Channel.LockStep, sb.ToString());
                }
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Have not recieved confirmation from player(s): ");
                foreach (int i in _pendingCommnads.WhosNotReady())
                {
                    sb.Append(i + ", ");
                }
                SkynetLogger.Info(Channel.LockStep, sb.ToString());
            }
            return(false);
        }
Exemplo n.º 27
0
        public void Send(string proto, int session, SpObject args)
        {
            _stream.Reset();

            if (proto != "heartbeat")
            {
                SkynetLogger.Info(Channel.NetDevice, "Send Request : " + proto + ", session : " + session);
            }

            _stream.Write((short)0);
            _rpc.Request(proto, args, session, _stream);
            var len = _stream.Length - 2;

            _stream.Buffer[0] = (byte)((len >> 8) & 0xff);
            _stream.Buffer[1] = (byte)(len & 0xff);

//			var mBuffer = new byte[2];
//			mBuffer[0] = (byte)((len >> 8) & 0xff);
//			mBuffer[1] = (byte)(len & 0xff);
//
//			SkynetLogger.Error(Channel.NetDevice,"xxxxxxxx  " + len + "hex:" + Utils.Crypt.Crypt.HexEncode(mBuffer));

            _transporter.Send(_stream.Buffer, _stream.Length);
        }
Exemplo n.º 28
0
 public void Action()
 {
     SkynetLogger.Info(Channel.LockStep, "Called Receiver.Action()");
 }
Exemplo n.º 29
0
 private void Open(object sender, EventArgs e)
 {
     SkynetLogger.Info(Channel.NetDevice, "ws client is connected" + _socket.IsConnected);
     _protocol = new Protocol(this);
     NetWorkChanged(NetWorkState.Connected);
 }
Exemplo n.º 30
0
 private void Error(object sender, ErrorEventArgs e)
 {
     SkynetLogger.Error(Channel.NetDevice, "WebSocket Has Error" + e.Message);
     NetWorkChanged(NetWorkState.Error);
 }