private Packet DecodePacketDecapsulated(Byte id, BinaryReaderBE reader)
        {
            Packet packet = null;

            switch ((PacketId)id)
            {
            case PacketId.ConnectedPing: packet = new ConnectedPing(); break;

            case PacketId.ConnectionRequest: packet = new ConnectionRequest(); break;

            case PacketId.ConnectionRequestAccepted: packet = new ConnectionRequestAccepted(); break;

            case PacketId.DisconnectionNotification: packet = new DisconnectionNotification(); break;

            default:
                packet = PacketConstructor(id);
                if (packet == null)
                {
                    throw new InvalidDataException("Unrecognized encapsulated packet ID");
                }
                break;
            }

            packet.Read(reader);
            return(packet);
        }
Example #2
0
        protected virtual void HandleConnectedPing(ConnectedPing message)
        {
            var packet = ConnectedPong.CreateObject();

            packet.sendpingtime = message.sendpingtime;
            packet.sendpongtime = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
            SendPacket(packet);
        }
        private void HandleConnectedPing(ConnectedPing packet)
        {
            var pong = new ConnectedPong();

            pong.ReceiveTime = packet.SendTime;
            pong.SendTime    = packet.SendTime;
            SendEncapsulated(pong, EncapsulatedReliability.Unreliable);
        }
Example #4
0
 /// <summary>
 ///     Handles the connected ping.
 /// </summary>
 /// <param name="message">The message.</param>
 private void HandleConnectedPing(ConnectedPing message)
 {
     SendPackage(new ConnectedPong
     {
         sendpingtime = message.sendpingtime,
         sendpongtime = DateTimeOffset.UtcNow.Ticks / TimeSpan.TicksPerMillisecond
     });
 }
Example #5
0
        public void SendConnectedPing()
        {
            var packet = new ConnectedPing()
            {
                sendpingtime = DateTime.UtcNow.Ticks
            };

            SendPackage(packet);
        }
Example #6
0
        protected virtual void HandleConnectedPing(ConnectedPing message)
        {
            ConnectedPong package = ConnectedPong.CreateObject();

            package.NoBatch      = true;
            package.ForceClear   = true;
            package.sendpingtime = message.sendpingtime;
            package.sendpongtime = DateTimeOffset.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
            SendPackage(package);
        }
Example #7
0
        private async Task UpdateAsync()
        {
            if (Evicted)
            {
                return;
            }

            //if (MiNetServer.FastThreadPool == null) return;

            if (!await _updateSync.WaitAsync(0))
            {
                return;
            }

            try
            {
                if (Evicted)
                {
                    return;
                }

                long now        = DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
                long lastUpdate = LastUpdatedTime.Ticks / TimeSpan.TicksPerMillisecond;

                if (lastUpdate + InactivityTimeout + 3000 < now)
                {
                    Evicted = true;
                    // Disconnect user
                    //ThreadPool.QueueUserWorkItem(o =>
                    {
                        Disconnect("Network timeout.");
                        Close();
                    }                    //);

                    return;
                }

                if (State != ConnectionState.Connected && CustomMessageHandler != null && lastUpdate + 3000 < now)
                {
                    Disconnect("Lost connection.");
                    return;
                }

                if (State == ConnectionState.Connected)
                {
                    lastUpdate = _lastPingTIme.Ticks / TimeSpan.TicksPerMillisecond;

                    if (now - lastUpdate > 2500)
                    {
                        ConnectedPing connectedPing = ConnectedPing.CreateObject();
                        connectedPing.sendpingtime = now;
                        //connectedPing.ReliabilityHeader.Reliability = Reliability.Unreliable;

                        SendPacket(connectedPing);

                        _pings.TryAdd(connectedPing.sendpingtime);
                        _lastPingTIme = DateTime.UtcNow;
                    }
                }
            }
            finally
            {
                _updateSync.Release();
            }
        }
Example #8
0
		/// <summary>
		///     Handles the connected ping.
		/// </summary>
		/// <param name="message">The message.</param>
		protected virtual void HandleConnectedPing(ConnectedPing message)
		{
			ConnectedPong package = ConnectedPong.CreateObject();
			package.sendpingtime = message.sendpingtime;
			package.sendpongtime = DateTimeOffset.UtcNow.Ticks/TimeSpan.TicksPerMillisecond;
			SendPackage(package, true);
		}
Example #9
0
        public void SendConnectedPing()
        {
            var packet = new ConnectedPing()
            {
                sendpingtime = DateTime.UtcNow.Ticks
            };

            SendPackage(packet);
        }
Example #10
0
        private void HandlePackage(Package message)
        {
            if (typeof(McpeBatch) == message.GetType())
            {
                OnBatch(message);

                return;
            }

            //TraceReceive(message);

            if (typeof(UnknownPackage) == message.GetType())
            {
                return;
            }

            else if (typeof(McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect)message;
                Log.InfoFormat("Disconnect {1}: {0}", msg.message, Username);
                //SendDisconnectionNotification();
                StopClient();
                return;
            }

            else if (typeof(ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing)message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            else if (typeof(McpeFullChunkData) == message.GetType())
            {
                OnFullChunkData(message);
                return;
            }

            else if (typeof(ConnectionRequestAccepted) == message.GetType())
            {
                OnConnectionRequestAccepted();
                return;
            }

            else if (typeof(McpeSetSpawnPosition) == message.GetType())
            {
                OnMcpeSetSpawnPosition(message);

                return;
            }

            else if (typeof(McpeStartGame) == message.GetType())
            {
                OnMcpeStartGame(message);

                return;
            }

            else if (typeof(McpeTileEvent) == message.GetType())
            {
                OnMcpeTileEvent(message);
                return;
            }
            else if (typeof(McpeAddEntity) == message.GetType())
            {
                OnMcpeAddEntity(message);

                return;
            }
            else if (typeof(McpeAddPlayer) == message.GetType())
            {
                OnMcpeAddPlayer(message);

                return;
            }
            else if (typeof(McpeSetEntityData) == message.GetType())
            {
                OnMcpeSetEntityData(message);
                return;
            }

            else if (typeof(McpeMovePlayer) == message.GetType())
            {
                //OnMcpeMovePlayer(message);
                return;
            }

            else if (typeof(McpeUpdateBlock) == message.GetType())
            {
                OnMcpeUpdateBlock(message);
                return;
            }

            else if (typeof(McpeLevelEvent) == message.GetType())
            {
                OnMcpeLevelEvent(message);
                return;
            }

            else if (typeof(McpeMobEffect) == message.GetType())
            {
                OnMcpeMobEffect(message);
                return;
            }

            else if (typeof(McpeSpawnExperienceOrb) == message.GetType())
            {
                OnMcpeSpawnExperienceOrb(message);
                return;
            }


            else if (typeof(McpeContainerSetContent) == message.GetType())
            {
                OnMcpeContainerSetContent(message);
                return;
            }

            else if (typeof(McpeCraftingData) == message.GetType())
            {
                OnMcpeCraftingData(message);
                return;
            }
        }
Example #11
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof(McpeBatch) == message.GetType())
            {
                McpeBatch batch = (McpeBatch)message;

                var messages = new List <Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    byte[] internalBuffer = destination.ToArray();
                    messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                }
                return;
            }

            TraceReceive(message);

            if (typeof(UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof(McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect)message;
                Log.Debug(msg.message);
                StopServer();
                return;
            }

            if (typeof(ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing)message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof(McpeFullChunkData) == message.GetType())
            {
                McpeFullChunkData msg   = (McpeFullChunkData)message;
                ChunkColumn       chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                if (chunk != null)
                {
                    Log.DebugFormat("Chunk X={0}", chunk.x);
                    Log.DebugFormat("Chunk Z={0}", chunk.z);

                    ClientUtils.SaveChunkToAnvil(chunk);
                }
                return;
            }

            if (typeof(ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                var t1 = new Timer(state => SendConnectedPing(), null, 2000, 5000);
                Thread.Sleep(50);
                SendLogin("Client12");
                return;
            }

            if (typeof(McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition)message;
                _spawn        = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int)_spawn.X;
                _level.SpawnY = (int)_spawn.Y;
                _level.SpawnZ = (int)_spawn.Z;

                return;
            }

            if (typeof(McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame)message;
                _entityId        = msg.entityId;
                _spawn           = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version   = 19133;
                _level.GameType  = msg.gamemode;

                ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof(McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent)message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof(McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof(McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof(McpeMovePlayer) == message.GetType())
            {
                McpeMovePlayer msg = (McpeMovePlayer)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);

                _currentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                SendMcpeMovePlayer();
                return;
            }

            if (typeof(McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock)message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof(McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent)message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }
        }
Example #12
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof(McpeBatch) == message.GetType())
            {
                Log.Debug("Processing Batch package");
                McpeBatch batch = (McpeBatch)message;

                var messages = new List <Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    destination.Position = 0;
                    NbtBinaryReader reader = new NbtBinaryReader(destination, true);
                    do
                    {
                        int    len            = reader.ReadInt32();
                        byte[] internalBuffer = reader.ReadBytes(len);
                        messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                    } while (destination.Position < destination.Length);                     // throw new Exception("Have more data");
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                    msg.PutPool();
                }
                return;
            }

            TraceReceive(message);

            if (typeof(UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof(McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect)message;
                Log.InfoFormat("Disconnect {1}: {0}", msg.message, Username);
                SendDisconnectionNotification();
                StopClient();
                return;
            }

            if (typeof(ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing)message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof(McpeFullChunkData) == message.GetType())
            {
                //McpeFullChunkData msg = (McpeFullChunkData) message;
                //ChunkColumn chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                //if (chunk != null)
                //{
                //	Log.DebugFormat("Chunk X={0}", chunk.x);
                //	Log.DebugFormat("Chunk Z={0}", chunk.z);

                //	//ClientUtils.SaveChunkToAnvil(chunk);
                //}
                return;
            }

            if (typeof(ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                //_connectedPingTimer = new Timer(state => SendConnectedPing(), null, 1000, 1000);
                Thread.Sleep(50);
                SendLogin(Username);
                return;
            }

            if (typeof(McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition)message;
                _spawn        = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int)_spawn.X;
                _level.SpawnY = (int)_spawn.Y;
                _level.SpawnZ = (int)_spawn.Z;

                return;
            }

            if (typeof(McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame)message;
                _entityId        = msg.entityId;
                _spawn           = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version   = 19133;
                _level.GameType  = msg.gamemode;

                //ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof(McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent)message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof(McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                //Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                //Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof(McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof(McpeMovePlayer) == message.GetType())
            {
                //McpeMovePlayer msg = (McpeMovePlayer) message;
                //Log.DebugFormat("Entity ID: {0}", msg.entityId);

                //CurrentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                //SendMcpeMovePlayer();
                return;
            }

            if (typeof(McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock)message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof(McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent)message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }

            if (typeof(McpeContainerSetContent) == message.GetType())
            {
                McpeContainerSetContent msg = (McpeContainerSetContent)message;
                Log.DebugFormat("Window ID: 0x{0:x2}, Count: {1}", msg.windowId, msg.slotData.Count);
                var slots = msg.slotData.GetValues();

                foreach (var entry in slots)
                {
                    MetadataSlot slot = (MetadataSlot)entry;
                    //Log.DebugFormat(" - Id: {0}, Metadata: {1}, Count: {2}", slot.Value.Item.Id, slot.Value.Item.Metadata, slot.Value.Count);
                }
                return;
            }

            if (typeof(McpeCraftingData) == message.GetType())
            {
                string fileName = Path.GetTempPath() + "Recipes_" + Guid.NewGuid() + ".txt";
                Log.Info("Writing recipes to filename: " + fileName);
                FileStream file = File.OpenWrite(fileName);

                McpeCraftingData   msg    = (McpeCraftingData)message;
                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine("static RecipeManager()");
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("Recipes = new Recipes");
                writer.WriteLine("{");
                writer.Indent++;

                foreach (Recipe recipe in msg.recipes)
                {
                    ShapelessRecipe shapelessRecipe = recipe as ShapelessRecipe;
                    if (shapelessRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapelessRecipe(new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", shapelessRecipe.Result.Id, shapelessRecipe.Result.Metadata, shapelessRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new List<ItemStack>");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (var itemStack in shapelessRecipe.Input)
                        {
                            writer.WriteLine(string.Format("new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", itemStack.Id, itemStack.Metadata, itemStack.Count));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }

                    ShapedRecipe shapedRecipe = recipe as ShapedRecipe;
                    if (shapedRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapedRecipe({0}, {1}, new ItemStack(ItemFactory.GetItem({2}, {3}), {4}),", shapedRecipe.Width, shapedRecipe.Height, shapedRecipe.Result.Id, shapedRecipe.Result.Metadata, shapedRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new Item[]");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (Item item in shapedRecipe.Input)
                        {
                            writer.WriteLine(string.Format("ItemFactory.GetItem({0}, {1}),", item.Id, item.Metadata));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }
                }

                writer.WriteLine("};");
                writer.Indent--;
                writer.WriteLine("}");
                writer.Indent--;

                writer.Flush();

                file.Close();
                Environment.Exit(0);
                return;
            }
        }
Example #13
0
 /// <summary>
 ///     Handles the connected ping.
 /// </summary>
 /// <param name="message">The message.</param>
 private void HandleConnectedPing(ConnectedPing message)
 {
     SendPackage(new ConnectedPong
     {
         sendpingtime = message.sendpingtime,
         sendpongtime = DateTimeOffset.UtcNow.Ticks/TimeSpan.TicksPerMillisecond
     });
 }