private async Task ConnectAsyncInternal(CancellationTokenSource cts = null) { if (Connected) { throw new InvalidOperationException(); } _client = new System.Net.Sockets.TcpClient(); if (cts == null) { await _client.ConnectAsync(_info.IpAddress, _info.Port); } else { try { await _client.ConnectAsync(_info.IpAddress, _info.Port).WithCancellation(cts.Token); } catch (OperationCanceledException) { Logger.LogWarning("Connecting interrupted"); return; } } Logger.Log($"Connected with {_info.IpAddress}:{_info.Port}"); }
private async void HandleCustomEvent(CustomEventData eventData) { try { Logger.Log("Handled custom event " + eventData.Code, NetworkLogType.Broadcasting); var code = (CustomEventCode)eventData.Code; switch (code) { case CustomEventCode.PlayerMoved: var movedEvent = DeserializeCustomEvent <PlayerMovedEventDTO>(eventData); var player = _simulation.Players.FirstOrDefault(_ => _.Id == movedEvent.PlayerId); if (player == null) { Debug.LogError($"Player {movedEvent.PlayerId} not found "); break; } player.MoveTo(movedEvent.Position); break; case CustomEventCode.FullUpdateRequest: if (!_isHost) { break; } var fullUpdateEvent = new FullUpdateEventDTO() { Simulation = _simulation.Save() }; var json = JsonConvert.SerializeObject(fullUpdateEvent, new Vector3Converter()); var bytes = Encoding.UTF8.GetBytes(json); await BroadcastEventAsync(bytes, (int)CustomEventCode.FullUpdate); break; case CustomEventCode.FullUpdate: var updateEvent = DeserializeCustomEvent <FullUpdateEventDTO>(eventData); _simulation.LoadFrom(updateEvent.Simulation); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception e) { Debug.LogException(e); } }
private async Task SendRequestAsync(IMessage message, OperationRequestCode code) { var request = new OperationRequest() { RequestCode = code, Payload = message.ToByteString(), }; Logger.Log($"Sending {CommandType.OpRequest} [{request.RequestCode}]", NetworkLogType.Broadcasting); await SendCommandAsync(CommandType.OpRequest, request); }
public async Task ConnectWithMasterServerAsync() { if (_connection != null && _connection.IsEstablished) { Logger.LogError("Already connected"); return; } _connection?.Dispose(); _connection = new Connection(DataHandler, ConnectionInfo); await _connection.InitAsync(async() => { await SendHandshakeAsync(); }); }
private void DataHandler(byte[] data) { Command command; try { command = Command.Parser.ParseFrom(data); } catch (Exception e) { Logger.LogError($"Exception occured while parsing command, received unexpected data: [{Encoding.ASCII.GetString(data)}]"); Debug.LogException(e); return; } Logger.Log($"Received command [{command.Type}] [{command.CalculateSize()}B]", NetworkLogType.Broadcasting); _commandsDispatcher.Invoke(() => HandleCommand(command)); }
private async Task SendCommandAsync(CommandType type, IMessage payload) { if (!_connection.IsEstablished) { //TODO: add queue buffer Logger.LogError("Failed to send command, disconnected with host."); return; } var command = new Command() { Type = type, Payload = payload.ToByteString() }; Logger.Log($"Sent command [{type}] [{command.CalculateSize()}B]", NetworkLogType.Broadcasting); await Task.Run(() => command.WriteTo(_connection.Stream)); }
protected override void HandleResponse(OperationResponse response) { switch (response.ResponseCode) { case OperationResponseCode.InvalidProtocol: case OperationResponseCode.InvalidLogin: case OperationResponseCode.InvalidPassword: Logger.LogError(response.ResponseCode.ToString()); break; case OperationResponseCode.HandshakeSuccess: Logger.Log(response.ResponseCode.ToString()); break; case OperationResponseCode.AlreadyConnected: Logger.LogWarning(response.ResponseCode.ToString()); break; } }
public async Task BroadcastEventAsync(byte[] serializedEvent, int eventCode) { var eventDataBase64 = serializedEvent == null ? string.Empty : Convert.ToBase64String(serializedEvent, 0, serializedEvent.Length); var customEvent = new CustomEventData() { Code = eventCode, Payload = ByteString.FromBase64(eventDataBase64) }; var message = new EventData() { Code = EventCode.CustomEvent, Payload = customEvent.ToByteString() }; Logger.Log($"Broadcast event {eventCode}", NetworkLogType.Broadcasting); await SendRequestAsync(message : message, OperationRequestCode.RaiseEvent); }
private void HandleCommand(Command command) { switch (command.Type) { case CommandType.OpResponse: var response = OperationResponse.Parser.ParseFrom(command.Payload); Logger.Log($"Received response [{response.ResponseCode}]", NetworkLogType.Broadcasting); HandleResponse(response); break; case CommandType.Event: var eventData = EventData.Parser.ParseFrom(command.Payload); Logger.Log($"Received event [{eventData.Code}]", NetworkLogType.Broadcasting); HandleEvent(eventData); break; default: throw new NotSupportedException(command.Type.ToString()); } }