private void HandleNewSocket(Socket socket) { if (socket == null) { return; } var remoteEndPoint = socket.RemoteEndPoint; this.Log(l => l.DebugFormat($"Game Client connected, Address {remoteEndPoint}")); ushort newPlayerId; var playerIdEventArgs = new RequestPlayerIdEventArgs(); if (!this.OnRequestPlayerId(playerIdEventArgs)) { // No Free Id, so disconnect the client this.Log(l => l.DebugFormat($"out of free id's... disconnecting the game client {remoteEndPoint}")); // MAYBE TODO: wait until an id is free? socket.Dispose(); } else { newPlayerId = playerIdEventArgs.PlayerId; this.Log(l => l.DebugFormat($"new player id {newPlayerId} for game client {remoteEndPoint}")); var connection = new Connection(socket, new Encryptor(), new Decryptor()); var remotePlayer = new RemotePlayer(newPlayerId, this.gameContext, this.mainPacketHandler, connection); this.OnPlayerConnected(remotePlayer); connection.Disconnected += (sender, e) => remotePlayer.Disconnect(); connection.BeginReceive(); } }
private bool OnRequestPlayerId(RequestPlayerIdEventArgs playerIdEventArgs) { var eventHandler = this.PlayerIdRequested; if (eventHandler != null) { eventHandler(this, playerIdEventArgs); } else { this.Log(l => l.Error($"Event {nameof(this.PlayerIdRequested)} was not handled.")); } return(!playerIdEventArgs.Cancel); }
private void OnPlayerIdRequested(object sender, RequestPlayerIdEventArgs e) { e.Cancel = !this.freePlayerIds.TryTake(out ushort newPlayerId); e.PlayerId = newPlayerId; }