private async Task AcceptPlayer() { Console.WriteLine("Start to accept player"); var playerConnection = new PlayerConnection(await listener.AcceptAsync()); PreparePlayer(playerConnection); }
protected override void Handle(UserPlayerDelete data, PlayerConnection connection) { var player = gameData.GetPlayer(data.PlayerId); if (player == null) { return; } worldProcessor.RemovePlayer(player); gameData.Remove(gameData.GetAppearance(player.AppearanceId)); gameData.Remove(gameData.GetTransform(player.TransformId)); gameData.Remove(gameData.GetAttributes(player.AttributesId)); gameData.Remove(gameData.GetProfessions(player.ProfessionsId)); var items = gameData.GetAllPlayerItems(player.Id); foreach (var item in items) { gameData.Remove(item); } gameData.Remove(player); SendPlayerList(connection); }
public bool RegisterPlayer(string username, string password, PlayerConnection connection) { password = SecurePasswordHasher.Hash(password); if (_playerDataManager.Exists(new PlayerDataLoaderArguments(username))) { var packet = new Packet(PacketType.LOGIN_FAIL, ChannelType.UNASSIGNED); packet.Message.Write("Account already exists!"); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); connection.Disconnect("byeFelicia"); return(false); } // Create their player. var descriptor = PlayerDescriptor.Create(username, password); descriptor.MapID = Settings.StartingMap; descriptor.Role = Settings.DefaultRole; var player = new Player(descriptor, connection); _playerDataManager.Save(player.Descriptor); this.AddPlayer(player); // Notify them that they successfully registered. var successPacket = new Packet(PacketType.REGISTER_SUCCESS, ChannelType.UNASSIGNED); player.SendPacket(successPacket, NetDeliveryMethod.Unreliable); return(true); }
private void Start() { gameManager = FindObjectOfType <GameManager>(); playerConnection = GameObject.FindGameObjectWithTag("MyConnection").GetComponent <PlayerConnection>(); InitializingCrazyWitchTime(); }
public void Dispose() { BotManager.RemoveBot(this); lock (SyncRoot) { if (!IsDisposed) { IsDisposed = true; } else { return; } Log.Info("Bot ({0}) disconnecting.", Id); PluginManager.StopPlugins(this); PlayManager.Stop(); PlayManager = null; PlayerConnection.Dispose(); PlayerConnection = null; ClientConnection.Dispose(); ClientConnection = null; } }
public bool RegisterPlayer(string username, string password, PlayerConnection connection) { // Make sure this player isn't already registered. if (File.Exists(Constants.FILEPATH_ACCOUNTS + username + ".acc")) { // Notify the requester that the specified username is already registered. var packet = new Packet(PacketType.REGISTRATION_FAIL, ChannelType.UNASSIGNED); packet.Message.Write("Account already registered!"); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); connection.Disconnect("byeFelicia"); this.EventOccured?.Invoke(this, new SubjectEventArgs("playerRegister", new object[] { false })); return(false); } // Create their player. var descriptor = PlayerDescriptor.Create(username, password); descriptor.MapID = Settings.StartingMap; descriptor.Role = Settings.DefaultRole; var player = new Player(descriptor, connection); player.Save(); _players.Add(player.UniqueID, player); // Notify them that they successfully registered. var successPacket = new Packet(PacketType.REGISTER_SUCCESS, ChannelType.UNASSIGNED); player.SendPacket(successPacket, NetDeliveryMethod.Unreliable); return(true); }
protected override void Handle(BotAuthRequest data, PlayerConnection connection) { logger.LogDebug("Bot Auth Request received. User: "******", Pass: "******"Sending Auth Response: " + (int)result); if (result != AuthResult.Success) { SendFailedLoginResult(connection, result); return; } connection.Disconnected -= ClientDisconnected; connection.Disconnected += ClientDisconnected; botManager.Add(botProvider.Create(connection, user)); // authenticated // send auth response SendSuccessLoginResult(connection); }
public void RegisterNetworkPlayer(PlayerConnection player) { if (players.Count <= 2) { // print("RegisterNetworkPlayer " + player.netId); // print(players.Count); // if (players.Find(p => p.playerIndex == 0) == null) { // player.playerIndex = 0; // } // else { // player.playerIndex = 1; // } // print(player.playerIndex); players.Add(player); // // Set Player Index // if (players.Find(p => p.playerIndex == 0) == null) { // player.playerIndex = 0; // } // else { // player.playerIndex = 1; // } } }
private void PreparePlayer(PlayerConnection playerConnection) { var task = new Task(() => { playerConnection.Send("Bem vindo ao jogo, digite seu nome:"); var playerName = playerConnection.Receive(); Console.WriteLine("Nome jogador: {0}", playerName); if (players.Count == Arena.MAX_PLAYERS_IN_THE_GAME) { playerConnection.Send("The game is already full"); playerConnection.Dispose(); } else { var player = new PlayerProcessor(playerName, arena, playerConnection); player.OnStop = () => players.Remove(player); player.OnStart = () => StartPlayers(); players.Add(player); } }); task.Start(); task.ContinueWith(t => Console.WriteLine("The player was prepared!")); }
protected override void Handle(PlayerObjectActionRequest data, PlayerConnection connection) { // actionId 0 is examine and is client side if (data.ActionId == 0) { logger.LogDebug("Player sent examine action, ignoring"); return; } logger.LogDebug("Player " + connection.Player.Id + " interacting with object: " + data.ObjectServerId + " action " + data.ActionId + " parameter " + data.ParameterId); var session = sessionManager.Get(connection.Player); var serverObject = session.Objects.Get(data.ObjectServerId); if (serverObject == null) { return; } var action = session.Objects.GetAction(serverObject, data.ActionId); if (action == null) { return; } // if we are already interacting with this object // ignore it. if (session.Objects.HasAcquiredLock(serverObject, connection.Player)) { logger.LogDebug("Player is already interacting with object. Ignore"); return; } worldProcessor.PlayerObjectInteraction(connection.Player, serverObject, action, data.ParameterId); }
protected override void Handle(UserPlayerSelect data, PlayerConnection connection) { var player = gameData.GetPlayer(data.PlayerId); if (player == null) { return; } // the disconnected event is only interesting after a player has // been selected, since the server wont keep track on a logged in user // without a selected player. // if the player is already in a game session // remove it from that session. var activeSession = sessionManager.Get(player); var targetSession = sessionManager.Get(data.SessionKey); if (player.SessionId != null && activeSession != null && activeSession != targetSession) { worldProcessor.RemovePlayer(player); } connection.Disconnected -= ClientDisconnected; connection.Disconnected += ClientDisconnected; connection.PlayerTag = player; connection.SessionKey = data.SessionKey; worldProcessor.LinkToGameSession(data.SessionKey, connection); }
public void Dispose() { BotManager.RemoveBot(this); lock (SyncRoot) { if (!IsDisposed) { IsDisposed = true; } else { return; } Log.Info("Bot disconnecting."); PluginManager.StopPlugins(this); PlayManager.Stop(); PlayManager = null; PlayerConnection.Dispose(); // before: logStream, PlayerConnection = null; QueryConnection.Dispose(); // before: logStream, QueryConnection = null; } }
public static void Main() { TcpListener server; Int32 port = 25250; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); server = new TcpListener(localAddr, port); server.Start(); int count = 1; Console.WriteLine("Waiting for a connection... "); while (true) { TcpClient connection = server.AcceptTcpClient(); PlayerConnection player = new PlayerConnection(connection); lock (_lock) { client_list.Add(count, player); } Thread thread = new Thread(clientThread); thread.Start(count); count++; } }
private void SendPlayerList(PlayerConnection connection) { var players = gameData.GetPlayers(connection.User).ToArray(); var appearances = players.Select(x => gameData.GetAppearance(x.AppearanceId)).ToArray(); connection.Send(UserPlayerList.Create(gameData, players, appearances), SendOption.Reliable); }
public bool LoginPlayer(string username, string password, PlayerConnection connection) { // Make sure this player isn't already in game. if (_players.Values.Any(player => player.Descriptor.Name == username)) { var packet = new Packet(PacketType.LOGIN_FAIL, ChannelType.UNASSIGNED); packet.Message.Write("Account already logged in!"); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); connection.Disconnect("byeFelicia"); return(false); } // If we've made it this far, we've confirmed that the requested account is not already logged into. // Let's make sure the password they provided us is valid. var playerDescriptor = _playerDataManager.Load(new PlayerDataLoaderArguments(username)); if (playerDescriptor == null) { // The account doesn't exist! var packet = new Packet(PacketType.LOGIN_FAIL, ChannelType.UNASSIGNED); packet.Message.Write("Account does not exist!"); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); connection.Disconnect("byeFelicia"); return(false); } // Check to see whether they were lying about that password... if (SecurePasswordHasher.Verify(password, playerDescriptor.Password)) { // Whoa, they weren't lying! // Let's go ahead and grant them access. // First, we'll add them to the list of online players. var player = new Player(playerDescriptor, connection); this.AddPlayer(player); // Now we'll go ahead and tell their client to make whatever preperations that it needs to. // We'll also tell them their super duper unique id. var packet = new Packet(PacketType.LOGIN_SUCCESS, ChannelType.UNASSIGNED); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); this.EventOccured?.Invoke(this, new SubjectEventArgs("playerLogin", new object[] { })); return(true); } else { var packet = new Packet(PacketType.LOGIN_FAIL, ChannelType.UNASSIGNED); packet.Message.Write("Incorrect password!"); connection.SendPacket(packet, NetDeliveryMethod.Unreliable); connection.Disconnect("byeFelicia"); return(false); } }
/// <summary> /// Operatin is syncrous so we can associate client with thread but shood to find way to do it though http context or smth same /// </summary> /// <param name="inputStream"></param> /// <param name="outputStream"></param> /// <param name="start"></param> /// <param name="end"></param> private static void CreatePartialContent(Stream outputStream, long position) { PlayerConnection.Initialize(); PlayerConnection.Play(); bool isFirstPacket = position == 0; DateTime lastSend = DateTime.MinValue; while (PlayerConnection.LastSeconds.Count < 3) { Thread.Sleep(1000); } while (true) { try { if (isFirstPacket) { outputStream.Write(PlayerConnection.Header, 0, PlayerConnection.Header.Length); isFirstPacket = false; } Thread.Sleep(950); int nextPacketIndex = PlayerConnection.LastSeconds.FindIndex(t => t.Key > lastSend); // we was created a spare time for the client if (nextPacketIndex == -1) { continue; } outputStream.Write(PlayerConnection.LastSeconds[nextPacketIndex].Value, 0, PlayerConnection.LastSeconds[nextPacketIndex].Value.Length); lastSend = PlayerConnection.LastSeconds[nextPacketIndex].Key; //Debug.WriteLine("Contetn pushed: " + DateTime.Now.ToString("mm:ss.FFF") + ", thread: " + Thread.CurrentThread.ManagedThreadId); } catch (System.Web.HttpException e) { Debug.WriteLine(e.ToString()); fs?.Close(); break; } catch (Exception e) { Debug.Write(e); fs?.Close(); break; } } }
private void SendFailedLoginResult(PlayerConnection connection, AuthResult result) { connection.Send(new BotAuthResponse() { Status = (int)result, SessionKeys = new byte[0] }, SendOption.Reliable); }
/// <summary> /// Draws the number of cards stored in currentDrawCount (incremented by PLUS cards) /// for the current player. /// </summary> public static void DrawCardsForPlayer(PlayerConnection player, int drawCount) { while (drawCount >= 0) { player.CmdGetCard(); drawCount--; } }
public StreamBot(ILogger logger, PlayerConnection connection, User botUser) { this.logger = logger; this.connection = connection; this.user = botUser; connection.UserTag = user; connection.BotTag = this; }
public PlayerProcessor(string playerName, Arena arena, PlayerConnection connection) { this.arena = arena; player = new Player(playerName, arena); this.connection = connection; player.OnStop = () => HandleGameStop(); player.OnDie = () => HandleGameStop(); StartCycle().ContinueWith(t => HandleGameStop()); }
public override void Process(Authenticate packet, PlayerConnection connection) { Console.WriteLine("sending time: " + timeKeeper.GetCurrentTime()); Player player = new Player(packet.PlayerId); tcpServer.PlayerAuthenticated(player, connection); tcpServer.SendPacketToPlayer(new TimeChange(timeKeeper.GetCurrentTime()), player); }
// Use this for initialization void Start() { _planeCollider = GameObject.FindGameObjectWithTag("Plane").GetComponent <Collider>(); GameObject[] gos = GameObject.FindGameObjectsWithTag("PlayerConnection"); if (gos.Any()) { _playerObject = gos.Select(go => go.GetComponent <PlayerConnection>()).Where(p => p.isLocalPlayer).First(); } }
public override Task StartAsync(PlayerConnection connection, CancellationToken cancellationToken = default) { if (!Initialized) { InitializeConfiguration(); } return(base.StartAsync(connection, cancellationToken)); }
private void SendSuccessLoginResult(PlayerConnection connection) { connection.Send(new AuthResponse() { Status = 0, SessionKeys = new byte[4] { 1, 2, 3, 4 } }, SendOption.Reliable); }
public override void OnLobbyServerSceneLoadedForPlayer(NetworkManager manager, GameObject lobbyPlayerGO, GameObject gamePlayerGO) { LobbyPlayer lobby = lobbyPlayerGO.GetComponent <LobbyPlayer>(); PlayerConnection playerConnection = gamePlayerGO.GetComponent <PlayerConnection>(); playerConnection.BuilderId = lobby.playerBuilderId; playerConnection.Allegiance = lobby.playerAllegiance; playerConnection.Name = lobby.playerName; playerConnection.Seed = lobby.Seed; }
public void AddPlayer(PlayerConnection connection) { if (!IsOpenWorldSession && Host == null) { Host = connection; session.UserId = connection.User.Id; } AddPlayer(connection.Player); }
// Use this for initialization void Start() { Debug.Log("STARTING ConnectToEditor"); editorID = -1; playerConnection = PlayerConnection.instance; playerConnection.RegisterConnection(EditorConnected); playerConnection.RegisterDisconnection(EditorDisconnected); playerConnection.Register(ConnectionMessageIds.fromEditorARKitSessionMsgId, HandleEditorMessage); m_session = null; }
public async void OnButton2_pressed() { var t = Task.Factory.StartNew(() => { TcpClient client = new TcpClient("localhost", 32500); return(new PlayerConnection(client)); }); _playerConnection = await t; _playerConnection.SendData(System.Text.Encoding.UTF8.GetBytes("Hi Server!")); }
public override void _Process(float delta) { if (_acceptTcpClientTask.IsCompleted) { var player = new PlayerConnection(_acceptTcpClientTask.Result); _playersConnection.Add(player); player.SendData(System.Text.Encoding.UTF8.GetBytes("Hi Player!")); _acceptTcpClientTask = _server.AcceptTcpClientAsync(); } }
public int GetPlayerIndex(PlayerConnection connection) { for (int i = 0; i < players.Count; i++) { if (connection == players[i]) { return(i); } } return(-1); }