Exemplo n.º 1
0
    //#Player Disconnect

    void onDisconnect(NetworkMessage msg)
    {
        DisconnectPacket packet = msg.ReadMessage <DisconnectPacket>();

        Debug.Log("disconnect");
        playerID.Remove(packet.name);
    }
Exemplo n.º 2
0
        private void HandleMessage(NetIncomingMessage msg)
        {
            PacketType type = (PacketType)msg.ReadByte();

            switch (type)
            {
            case PacketType.ChatMessage:
                ChatMessagePacket chatPacket = new ChatMessagePacket();
                chatPacket.Unpack(msg);
                ChatManager.Instance.addMessage(chatPacket.username, chatPacket.message);
                break;

            case PacketType.PlayerPosition:
                PlayerPositionPacket posPacket = new PlayerPositionPacket();
                posPacket.Unpack(msg);
                ClientGameManager.Instance.HandleNewPlayerPosition(posPacket);
                break;

            case PacketType.Disconnect:
                DisconnectPacket disPacket = new DisconnectPacket();
                disPacket.Unpack(msg);
                ClientGameManager.Instance.HandlePlayerDisconnect(disPacket.username);
                break;

            case PacketType.MobPosition:
                MobPositionPacket mpPacket = new MobPositionPacket();
                mpPacket.Unpack(msg);
                ClientGameManager.Instance.HandleMobMovement(mpPacket);
                break;
            }
        }
Exemplo n.º 3
0
        void HandleDisconnect(Session session, DisconnectPacket p)
        {
            if (session.State == SessionState.Disconnected)
            {
                log.Info($"already disconnected: id={session.ID}");
                return;
            }

            // 연결 종료는 소켓이 끊어질떄도 있고
            // 유저가 직접 종료시키는 경우도 있다
            // disconnect를 여러번 호출해도 꺠지지 않도록 하자
            // 연결 끊은것을 연결 종료 패킷처럼 다루면
            // 상위 레이어에서의 처리가 간단해진다
            if (session.WorldID != null)
            {
                var leave = new WorldLeavePacket();
                var codec = new PacketCodec();
                var bytes = codec.Encode(leave);
                var pair  = new ReceivedPacket <WorldLeavePacket>(session, bytes);
                HandleWorldLeave(session, pair);
            }

            log.Info($"disconnect: id={session.ID}");
            var disconnect = new DisconnectPacket();

            session.SendLazy(disconnect);

            // 연결 끊어도 된다는 표시 해두기. 언제 끊어도 상관 없어야한다
            NetworkStack.Session.CloseSessionActive(session);
        }
Exemplo n.º 4
0
        public void TestMultiplePacket()
        {
            var codec = new PacketCodec();

            var a = new ConnectPacket();
            var b = new DisconnectPacket();

            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream);
            var data   = ByteJoin.Combine(codec.Encode(a), codec.Encode(b));

            var reader = new BinaryReader(new MemoryStream(data));
            var iter   = new PacketEnumerator(reader);

            // 1st packet
            {
                Assert.True(iter.MoveNext());
                ConnectPacket p;
                Assert.True(iter.GetCurrent(out p));
                Assert.Equal(a, p);
            }

            // 2nd packet
            {
                Assert.True(iter.MoveNext());
                DisconnectPacket p;
                Assert.True(iter.GetCurrent(out p));
                Assert.Equal(b, p);
            }

            // end of stream
            {
                Assert.False(iter.MoveNext());
            }
        }
        public void OnExit(object sender, EventArgs e)
        {
            //TODO: gracefully close player connections
            DisconnectPacket myDisconnect = new DisconnectPacket(InternalSettings.Username);

            Send(myDisconnect, NetDeliveryMethod.ReliableOrdered);
        }
Exemplo n.º 6
0
        public static Packet ConvertToPacket(this byte[] buffer, SocketReceivedResult socketReceiveResult)
        {
            Packet receivedPacket = null;
            var    eventType      = buffer.GetSocketEventType();

            switch (eventType)
            {
            case PacketTypeEnum.Connection:
                receivedPacket = new ConnectionPacket();
                break;

            case PacketTypeEnum.Ping:
                receivedPacket = new PingPacket();
                break;

            case PacketTypeEnum.Disconnect:
                receivedPacket = new DisconnectPacket();
                break;

            case PacketTypeEnum.Movement:
                receivedPacket = new MovementPacket();
                break;

            default:
                Log.Error("Unknown packet type, cannot handle them");
                break;
            }

            receivedPacket.Deserialize(buffer);
            receivedPacket.SetHeader(eventType, socketReceiveResult.RemoteEndPoint);

            return(receivedPacket);
        }
Exemplo n.º 7
0
        public void Close(string message)
        {
            DisconnectPacket disconnectPacket = new DisconnectPacket();

            disconnectPacket.Message = message;

            SendDataPacket(disconnectPacket);
        }
        //-----------------------------------------------------------------------------------------
        public override void RemoveClient(string name)
        {
            DisconnectPacket packet = new DisconnectPacket(name);

            SendPacketToClient(packet, name);
            Thread.Sleep(50);
            RemovingClient(name);
        }
Exemplo n.º 9
0
    private void OnDisconnect()
    {
        Debug.Log("disconnected");
        DisconnectPacket packet = new DisconnectPacket();

        packet.name = player.playerName;
        con.Send(PacketTypes.DISCONNECT, packet);
    }
Exemplo n.º 10
0
        public void DisconnectPacket(string userName)
        {
            DisconnectPacket packet = new DisconnectPacket(userName);

            SendPacket(packet);
            Thread.Sleep(10);
            Disconnect();
        }
Exemplo n.º 11
0
        //-----------------------------------------------------------------------------------------
        public override void Stop()
        {
            DisconnectPacket packet = new DisconnectPacket(_username);

            Send(packet);
            Thread.Sleep(50);
            Disconnect();
        }
Exemplo n.º 12
0
        private void WaitingLobby_FormClosing(object sender, FormClosingEventArgs e)
        {
            Send(new LeaveLobbyPacket());


            DisconnectPacket packet = new DisconnectPacket();

            Send(packet);
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Disconnects this instance with the specified reason.
        /// </summary>
        /// <param name="reason">The reason.</param>
        public void Disconnect(string reason)
        {
            NetworkMessage message = new NetworkMessage(Xtea);

            DisconnectPacket.Add(message, reason);

            Send(message);
            Close();
        }
Exemplo n.º 14
0
        public void TestSerde()
        {
            var a = new DisconnectPacket()
            {
            };
            var b = SerializeAndDeserialize(a);

            Assert.Equal(a, b);
        }
Exemplo n.º 15
0
        public static void HandlePacketDisconnect(TestClient client, DisconnectPacket dp)
        {
            client.Dispose();

            using (StreamWriter sw = new StreamWriter(String.Format("disconnect_reason_{0}.log", client.UserName), true))
            {
                sw.WriteLine("{0} - {1}", DateTime.Now, dp.Reason);
            }
        }
Exemplo n.º 16
0
        bool TryDecodePacket(IChannelHandlerContext context, IByteBuffer buffer, out Packet packet)
        {
            if (!buffer.IsReadable(2))
            {
                packet = null;
                return(false);
            }

            byte signature = buffer.ReadByte();

            if (!TryDecodeRemainingLength(buffer, out int remainingLength) || !buffer.IsReadable(remainingLength))
            {
                packet = null;
                return(false);
            }

            var fixedHeader = new FixedHeader(signature, remainingLength);

            switch (fixedHeader.PacketType)
            {
            case PacketType.CONNECT: packet = new ConnectPacket(); break;

            case PacketType.CONNACK: packet = new ConnAckPacket(); break;

            case PacketType.DISCONNECT: packet = new DisconnectPacket(); break;

            case PacketType.PINGREQ: packet = new PingReqPacket(); break;

            case PacketType.PINGRESP: packet = new PingRespPacket(); break;

            case PacketType.PUBACK: packet = new PubAckPacket(); break;

            case PacketType.PUBCOMP: packet = new PubCompPacket(); break;

            case PacketType.PUBLISH: packet = new PublishPacket(); break;

            case PacketType.PUBREC: packet = new PubRecPacket(); break;

            case PacketType.PUBREL: packet = new PubRelPacket(); break;

            case PacketType.SUBSCRIBE: packet = new SubscribePacket(); break;

            case PacketType.SUBACK: packet = new SubAckPacket(); break;

            case PacketType.UNSUBSCRIBE: packet = new UnsubscribePacket(); break;

            case PacketType.UNSUBACK: packet = new UnsubscribePacket(); break;

            default:
                throw new DecoderException("Unsupported Message Type");
            }
            packet.FixedHeader = fixedHeader;
            packet.Decode(buffer);

            return(true);
        }
Exemplo n.º 17
0
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            DisconnectPacket dc = new DisconnectPacket(Form1.login);

            Packet.Send(dc, Form1.stream);

            Thread.Sleep(100);

            Application.Exit();
        }
Exemplo n.º 18
0
        private void TCPClientMethod(int index)
        {
            Packet receivedPacket;

            //loop to allow continuous communication
            while ((receivedPacket = _clients[index].TCPRead()) != null)
            {
                try
                {
                    switch (receivedPacket.EPacketType)
                    {
                    case PacketType.EMPTY:
                        EmptyPacket emptyPacket = (EmptyPacket)receivedPacket;
                        break;

                    case PacketType.LOGIN:
                        LoginPacket loginPacket = (LoginPacket)receivedPacket;
                        _clients[index].clientData.posX        = loginPacket.SpriteX;
                        _clients[index].clientData.posY        = loginPacket.SpriteY;
                        _clients[index].clientData.playerIndex = (_clients.Count - 1);

                        //confirm connection to joining player
                        JoinConfirmationPacket joinConfirmationPacket = new JoinConfirmationPacket((_clients.Count - 1), GetAllPlayerXValues(), GetAllPlayerYValues());
                        _clients[index].TCPSend(joinConfirmationPacket);

                        PlayerJoinPacket playerJoinPacket = new PlayerJoinPacket(_clients.Count - 1, loginPacket.SpriteX, loginPacket.SpriteY);
                        Console.WriteLine(_clients.Count);
                        TCPSendPacketToAll(playerJoinPacket);
                        Console.WriteLine("PACKETS SENT");
                        break;

                    case PacketType.DISCONNECT:
                        DisconnectPacket disconnectRequestPacket = (DisconnectPacket)receivedPacket;
                        break;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[Error] " + e.Message + e.StackTrace);
                    break;
                }
            }

            try
            {
                _clients[index].Close();

                //Take client out of client ConcurrentBag
                _clients.TryRemove(index, out Client c);
            }
            catch (Exception e)
            {
                Console.WriteLine("[Error] " + e.Message + e.StackTrace);
            }
        }
Exemplo n.º 19
0
        public async Task DisconnectAsync(ClientConnection client, string reason)
        {
            _connectionManager.RemoveConnection(client.Id);

            var disconnectPacket = new DisconnectPacket(client.Id, reason);

            await _socketManager.SendAsync(
                data : disconnectPacket.Serialize(),
                recipients : _connectionManager.GetAllAvailableRecipients()
                );
        }
Exemplo n.º 20
0
 public void SendDisconnectPacket()
 {
     if (Data.CHARACTER_ID != 0)
     {
         DisconnectPacket dcPacket = new DisconnectPacket(Data.CHARACTER_ID);
         SubPacket        packet   = new SubPacket(GamePacketOpCode.Disconnect, Data.CHARACTER_ID, 0, dcPacket.GetBytes(), SubPacketTypes.GamePacket);
         var packetToSend          = BasePacket.CreatePacket(packet, PacketProcessor.isAuthenticated, false);
         packetToSend.header.connectionType = (ushort)BasePacketConnectionTypes.Connect;
         socket.Send(packetToSend.GetPacketBytes());
     }
 }
Exemplo n.º 21
0
        public static void ReadDisconnect(Client client, PacketReader reader)
        {
            DisconnectPacket dp = new DisconnectPacket();

            dp.Read(reader);

            if (!reader.Failed)
            {
                Client.HandlePacketDisconnect(client, dp);
            }
        }
Exemplo n.º 22
0
        protected void disconnect(string reason = "Server Closed")
        {
            if (this.loggedIn)
            {
                DisconnectPacket packet = new DisconnectPacket();
                packet.type    = DisconnectPacket.TYPE_GENERIC;
                packet.message = reason;
                packet.encode();

                _client.Send(packet.getEncoded());
            }
        }
Exemplo n.º 23
0
    public override void ProcessPacket(BasePacket receivedPacket)
    {
        if (!isAuthenticated && receivedPacket.isAuthenticated())
        {
            isAuthenticated = true;
        }
        List <SubPacket> subPackets = receivedPacket.GetSubpackets();

        foreach (SubPacket subPacket in subPackets)
        {
            DoAuthenticationChecks(receivedPacket, subPacket);

            if (!receivedPacket.isAuthenticated())
            {
                Debug.Log("Not authenticated.. Do something here");
                throw new NotImplementedException();
            }
            else
            {
                switch (subPacket.gameMessage.opcode)
                {
                case ((ushort)GamePacketOpCode.NearbyActorsQuery):
                    PositionPacket pos     = new PositionPacket(subPacket.data);
                    ActorWrapper   wrapper = new ActorWrapper(pos.XPos, pos.YPos, pos.Playable, pos.ActorId);
                    GameEventManager.TriggerActorNeedsDrawing(new GameEventArgs {
                        Actor = wrapper
                    });

                    break;

                case ((ushort)GamePacketOpCode.PositionQuery):
                    PositionPacket otherCharacterPos = new PositionPacket(subPacket.data);
                    GameEventManager.TriggerPollerResponse(new GameEventArgs {
                        PollerPositionPacket = otherCharacterPos
                    });

                    break;

                case ((ushort)GamePacketOpCode.OtherPlayerDisconnected):
                    DisconnectPacket dc = new DisconnectPacket(subPacket.data);
                    Character        playerToDisconnect;
                    if (Data.drawnCharacters.TryGetValue(dc.CharacterId, out playerToDisconnect))
                    {
                        Data.drawnCharacters.Remove(dc.CharacterId);
                        destroyer.AddCharacter(playerToDisconnect);
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 24
0
        protected override void OnClose(CloseEventArgs e)
        {
            log.Info($"OnClose: code={e.Code}, reason={e.Reason}, wasClean={e.WasClean}");

            // 소켓이 닫히는건 아래쪽 레이어에서 감지한다
            // 상위레이어로 소켓이 닫혔다는걸 알려주기
            var p     = new DisconnectPacket();
            var codec = new PacketCodec();

            transport.Recv(codec.Encode(p));

            NetworkStack.Session.CloseSessionPassive(session);
            session = null;
        }
Exemplo n.º 25
0
    private void OnDisconnect()
    {
        Debug.Log("disconnected");
        DisconnectPacket packet = new DisconnectPacket();

        packet.name = player.playerName;
        List <byte[]> questList = (List <byte[]>)Tools.byteArrayToObject(packet.questListInBytes);

        foreach (Quest q in player.getQuests())
        {
            questList.Add(Tools.objectToByteArray(q));
        }
        con.Send(PacketTypes.DISCONNECT, packet);
    }
Exemplo n.º 26
0
        /// <summary>
        /// Disconnects the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="packet">The packet.</param>
        public async Task Disconnect(IChannelHandlerContext context, DisconnectPacket packet)
        {
            var deviceId = await _channelService.GetDeviceId(context.Channel);

            var message = TransportMessage.CreateInvokeMessage(new RemoteInvokeMessage
            {
                ServiceId = "Disconnect", Parameters = new Dictionary <string, object> {
                    { "packet", packet }
                }
            });

            WirteDiagnosticBefore(message, context.Channel.RemoteAddress.ToString(), deviceId, packet.PacketType);
            await _channelService.Close(deviceId, true);

            WirteDiagnosticAfter(message);
        }
Exemplo n.º 27
0
        private void handlePacket(int pid, Packet packet)
        {
            switch (pid)
            {
            case SynapseInfo.DISCONNECT_PACKET:
                DisconnectPacket disconnectPacket = (DisconnectPacket)packet;
                disconnectPacket.decode();
                this.loggedIn = false;

                Message("Disconnect received: " + disconnectPacket.message);

                break;

            case SynapseInfo.INFORMATION_PACKET:
                InformationPacket packetInformation = (InformationPacket)packet;
                packetInformation.decode();

                if (packetInformation.type == InformationPacket.TYPE_LOGIN)
                {
                    if (packetInformation.message == InformationPacket.INFO_LOGIN_SUCCESS)
                    {
                        this.loggedIn = true;
                        Message("Login sucess to " + address + ":" + port);
                    }
                    else
                    {
                        Message("Login failed to " + address + ":" + port);
                    }
                }
                else if (packetInformation.type == InformationPacket.TYPE_CLIENT_DATA)
                {
                    var clientHash = Newtonsoft.Json.JsonConvert.DeserializeObject(packetInformation.message);
                    //TODO: pass into ClientData object
                }

                break;

            case SynapseInfo.PLAYER_LOGIN_PACKET:
                PlayerLoginPacket packetLogin = (PlayerLoginPacket)packet;
                packetLogin.decode();
                Message("Player joining...");
                //  Message("Player UUID: " + packetLogin.uuid.ToString());
                Message("Player address: " + packetLogin.address);

                break;
            }
        }
Exemplo n.º 28
0
        Packet DecodePacketInternal(IByteBuffer buffer, byte packetSignature, ref int remainingLength)
        {
            Packet packet;
            var    fixedHeader = new FixedHeader(packetSignature, remainingLength);

            switch (fixedHeader.PacketType)
            {
            case PacketType.CONNECT: packet = new ConnectPacket(); break;

            case PacketType.CONNACK: packet = new ConnAckPacket(); break;

            case PacketType.DISCONNECT: packet = new DisconnectPacket(); break;

            case PacketType.PINGREQ: packet = new PingReqPacket(); break;

            case PacketType.PINGRESP: packet = new PingRespPacket(); break;

            case PacketType.PUBACK: packet = new PubAckPacket(); break;

            case PacketType.PUBCOMP: packet = new PubCompPacket(); break;

            case PacketType.PUBLISH: packet = new PublishPacket(); break;

            case PacketType.PUBREC: packet = new PubRecPacket(); break;

            case PacketType.PUBREL: packet = new PubRelPacket(); break;

            case PacketType.SUBSCRIBE: packet = new SubscribePacket(); break;

            case PacketType.SUBACK: packet = new SubAckPacket(); break;

            case PacketType.UNSUBSCRIBE: packet = new UnsubscribePacket(); break;

            case PacketType.UNSUBACK: packet = new UnsubscribePacket(); break;

            default:
                throw new DecoderException("Unsupported Message Type");
            }
            packet.FixedHeader = fixedHeader;
            packet.Decode(buffer);
            remainingLength = packet.RemaingLength;
            return(packet);
        }
Exemplo n.º 29
0
        private void HandlePositionQuery(SubPacket subPacket)
        {
            var targetActor = subPacket.header.targetId;
            var sourceActor = subPacket.header.sourceId;

            if (WorldServer.mConnectedPlayerList.TryGetValue(targetActor, out Character character))
            {
                PositionPacket positionQuery = new PositionPacket(character.XPos, character.YPos,
                                                                  true, character.CharacterId);
                SubPacket positionQuerySp = new SubPacket(GamePacketOpCode.PositionQuery, 0, targetActor,
                                                          positionQuery.GetBytes(), SubPacketTypes.GamePacket);
                client.QueuePacket(positionQuerySp, true, false); //TODO: isAuthed
            }
            else
            {
                Console.WriteLine("Sending info to {0} that character ID:{1} has disconnected", client.GetFullAddress(), targetActor);
                DisconnectPacket disconnectedPlayer       = new DisconnectPacket(targetActor);
                SubPacket        disconnectedPlayerPacket = new SubPacket(GamePacketOpCode.OtherPlayerDisconnected, 0, targetActor,
                                                                          disconnectedPlayer.GetBytes(), SubPacketTypes.GamePacket);
                client.QueuePacket(disconnectedPlayerPacket, true, false);
            }
        }
Exemplo n.º 30
0
        public void Close(string reason, bool clientDisconnect = false)
        {
            PlayerQuitEventArgs playerQuitEvent = new PlayerQuitEventArgs(this, $"§e{this.Name} が世界を去りました", reason);

            PlayerEvents.OnPlayerQuit(playerQuitEvent);
            reason = playerQuitEvent.Reason;
            if (!string.IsNullOrEmpty(reason))
            {
                DisconnectPacket pk = new DisconnectPacket();
                pk.Message = reason;

                this.SendPacket(pk, true);
            }
            if (!string.IsNullOrEmpty(playerQuitEvent.QuitMessage))
            {
                Server.Instance.BroadcastMessage(playerQuitEvent.QuitMessage);
            }
            Logger.Info($"§e{this.Name} left the game");

            this.Save();

            if (this.World != null)
            {
                this.World.UnLoadChunks(this);
            }

            this.Closed = true;

            this.World?.RemovePlayer(this);

            Server.Instance.RemovePlayer(this.EntityID);

            if (!clientDisconnect)
            {
                Server.Instance.NetworkManager.PlayerClose(this.EndPoint, reason);
            }

            this.PlayerListEntry = null;
        }
Exemplo n.º 31
0
        /// <summary>
        ///     Disconnects from the host.
        /// </summary>
        /// <returns>True if the host was force disconnected.</returns>
        /// <param name="force">If set to true, the connection will be immediately terminated, otherwise it will ask the server to terminate it.</param>
        public async Task<bool> DisconnectAsync(bool force = false)
        {
            if (force == true)
            {
                Logger.Info("Forcing disconnect of socket.", LoggerVerboseLevel.High);

                DisposeSocket(false);
                return true;
            }
            else
            {
                // Disconnect peers.
                foreach (Connection conn in m_peers.ToList())
                {
                    await conn.DisconnectAsync(false);
                }
                
                DisconnectPacket packet = new DisconnectPacket();
                SendPacket(packet);

                // Wait until we are disconnected!
                long timeout = System.Environment.TickCount + Settings.CONNECTION_DISCONNECT_TIMEOUT;
                while (m_connected == true)
                {
                    // Force close the socket.
                    if (System.Environment.TickCount >= timeout)
                    {
                        Logger.Info("Forcing disconnect of socket.", LoggerVerboseLevel.High);

                        DisposeSocket(false);
                        return true;
                    }

                    await Task.Delay(10);
                }

                DisposeSocket(false);
                return true;
            }

            Logger.Info("Socket disconnected successfully.", LoggerVerboseLevel.High);

            return false;
        }
Exemplo n.º 32
0
        private void HandleDisconnect(Client client, DisconnectPacket packet)
        {
            if (client.LoggedIn && client.Player.Username.Length > 0)
            {
                Server.BroadcastPacket(new ChatMessagePacket("", ChatColor.Yellow + client.Player.Username + " left the game."));
                Server.BroadcastPacket(new DestroyEntityPacket(client.Player.EntityID));
                Logger.Info(client.Player.Username + " left the game. (" + packet.Reason + ")");
            }

            client.Dispose();
        }