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); }
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(); } }
public void Start() { SkynetLogger.Error(Channel.NetDevice, "++++++Skynet Client Start++++"); _login = new TestLoginTcp(Protocol); _login.Run(ProcessLoginResp); }
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(); } }
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++++"); }
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"); } } }); } }
void VerifySucess(SpObject sp) { SkynetLogger.Info(Channel.NetDevice, "is OnVerifySucess"); _client.StartHeartBeatService(); //TODO: 请求各模块信息 }
//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()); } } }); }
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); } }
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); } }
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(); } }
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); } }
public void RawSend(byte[] data, int length) { if (length >= 512) { SkynetLogger.Error(Channel.Udp, "Send Data overload 1 MTU"); } _udpClient.SendAsync(data, length); }
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); }
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); }
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 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); }
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(); }); } }
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(); } }
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 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 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"); }); }
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(); }
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); } }
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()}"); } }
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); }
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); }
public void Action() { SkynetLogger.Info(Channel.LockStep, "Called Receiver.Action()"); }
private void Open(object sender, EventArgs e) { SkynetLogger.Info(Channel.NetDevice, "ws client is connected" + _socket.IsConnected); _protocol = new Protocol(this); NetWorkChanged(NetWorkState.Connected); }
private void Error(object sender, ErrorEventArgs e) { SkynetLogger.Error(Channel.NetDevice, "WebSocket Has Error" + e.Message); NetWorkChanged(NetWorkState.Error); }