Exemple #1
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");
                        }
                    }
                });
            }
        }
        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);
        }
        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();
            }
        }
Exemple #4
0
        void VerifySucess(SpObject sp)
        {
            SkynetLogger.Info(Channel.NetDevice, "is OnVerifySucess");

            _client.StartHeartBeatService();
            //TODO: 请求各模块信息
        }
        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();
            }
        }
        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);
        }
Exemple #7
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);
        }
Exemple #8
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);
        }
        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(); });
            }
        }
Exemple #10
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();
            }
        }
        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();
        }
Exemple #12
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");
            });
        }
Exemple #13
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());
                }
            });
        }
        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);
        }
Exemple #15
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);
        }
Exemple #16
0
        public void Connect(string host, int port, AuthPackageReq req, Action <int, AuthPackageResp> loginCallBack)
        {
            if (_netWorkState != NetWorkState.Closed)
            {
                SkynetLogger.Info(Channel.NetDevice, "LoginClient has connect action");
                return;
            }

            _timeoutEvent.Reset();
            _eventManager = new EventManager(req, loginCallBack, this);

            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);
            }

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

            _socket.BeginConnect(ie, new AsyncCallback((result) =>
            {
                try
                {
                    _socket.EndConnect(result);
                    _protocol = new Protocol(this, this._socket);
                    NetWorkChanged(NetWorkState.Connected);
                }
                catch (SocketException)
                {
                    if (_netWorkState != NetWorkState.Timeout)
                    {
                        NetWorkChanged(NetWorkState.Error);
                    }
                    Dispose();
                }
                finally
                {
                    _timeoutEvent.Set();
                }
            }), _socket);

            if (!_timeoutEvent.WaitOne(_timeoutMSec, false))
            {
                return;
            }
            if (_netWorkState == NetWorkState.Connected || _netWorkState == NetWorkState.Error)
            {
                return;
            }
            NetWorkChanged(NetWorkState.Timeout);
            Dispose();
        }
Exemple #17
0
 public void Action()
 {
     SkynetLogger.Info(Channel.LockStep, "Called Receiver.Action()");
 }
Exemple #18
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);
 }