Exemplo n.º 1
0
        public void StartListening()
        {
            int port = Server.ServerSettings.Port;

            if (!NetUtils.PortAvailability(port))
            {
                ConsoleFunctions.WriteErrorLine("Port already in use... Shutting down server... [{0}]", port);
                Server.StopServer();
                return;
            }
            ConsoleFunctions.WriteInfoLine("Starting server on port... {0}", port);
            _serverListener = new TcpListener(IPAddress.Any, port);
            if (_serverListener == null)
            {
                ConsoleFunctions.WriteErrorLine("An error occured when starting the client listener.. Null TCPListener..");
                return;
            }
            _serverListener.Start();
            ConsoleFunctions.WriteInfoLine("Ready & looking for client connections... ");
            ConsoleFunctions.WriteInfoLine("To shutdown the server safely press CTRL+C or use stop/shutdown!");
            while (_serverListener.Server.IsBound)
            {
                TcpClient client = _serverListener.AcceptTcpClient();
                ConsoleFunctions.WriteDebugLine("A new client has been accepted.");
                new Task(() =>
                {
                    HandleClientConnection(client);
                }).Start();
            }
        }
Exemplo n.º 2
0
 public AnvilLevel(string worldname)
 {
     Difficulty = 0;
     LvlName    = worldname;
     LevelType  = LvlType.Default;
     Generator  = new AnvilWorldProvider(worldname);
     ConsoleFunctions.WriteDebugLine("Level Type: Anvil");
 }
Exemplo n.º 3
0
 public NetherLevel(string worldname)
 {
     Difficulty = 0;
     LvlName    = worldname;
     LevelType  = LvlType.Default;
     Generator  = new NetherWorldProvider(worldname);
     ConsoleFunctions.WriteDebugLine("Level Type: Nether");
     Dimension = -1;
 }
Exemplo n.º 4
0
 public StandardLevel(string worldname)
 {
     Difficulty = 0;
     LvlName    = worldname;
     LevelType  = LvlType.Default;
     Generator  = new StandardWorldProvider(worldname);
     ConsoleFunctions.WriteDebugLine("Level Type: Standard");
     DefaultGamemode = Gamemode.Creative;
 }
Exemplo n.º 5
0
        internal void LoadPlugins()
        {
            if (Config.GetProperty("PluginDisabled", false))
            {
                return;
            }
            var pluginDirectory = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            pluginDirectory = Config.GetProperty("PluginDirectory", pluginDirectory);
            if (pluginDirectory != null)
            {
                pluginDirectory = Path.GetFullPath(pluginDirectory);

                foreach (var pluginPath in Directory.GetFiles(pluginDirectory, "*.dll", SearchOption.AllDirectories))
                {
                    var newAssembly = Assembly.LoadFile(pluginPath);
                    var types       = newAssembly.GetExportedTypes();
                    foreach (var type in types)
                    {
                        try
                        {
                            if (!type.IsDefined(typeof(PluginAttribute), true) && !typeof(IPlugin).IsAssignableFrom(type))
                            {
                                continue;
                            }
                            if (type.IsDefined(typeof(PluginAttribute), true))
                            {
                                var pluginAttribute = Attribute.GetCustomAttribute(type, typeof(PluginAttribute), true) as PluginAttribute;
                                if (pluginAttribute != null)
                                {
                                    if (!Config.GetProperty(pluginAttribute.PluginName + ".Enabled", true))
                                    {
                                        continue;
                                    }
                                }
                            }
                            var ctor = type.GetConstructor(Type.EmptyTypes);
                            if (ctor != null)
                            {
                                var plugin = ctor.Invoke(null);
                                _plugins.Add(plugin);
                                LoadCommands(type);
                                LoadOnPlayerJoin(type);
                            }
                        }
                        catch (Exception ex)
                        {
                            ConsoleFunctions.WriteWarningLine("Failed loading plugin type " + type + " as a plugin.");
                            ConsoleFunctions.WriteDebugLine("Plugin loader caught exception: " + ex);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        private void HandleClientCommNew(object client)
        {
            TcpClient     tcpClient    = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            ClientWrapper Client       = new ClientWrapper(tcpClient);

            //Buffer size of 4096 Bytes, reason: I guess we don't need more?
            byte[] message = new byte[4096];
            int    bytesRead;

            while (true)
            {
                bytesRead = 0;
                try
                {
                    //if (clientStream.DataAvailable)
                    bytesRead = clientStream.Read(message, 0, 4096);
                    if (bytesRead > 0)
                    {
                        ConsoleFunctions.WriteDebugLine("Packet received. Time: " + DateTime.Now.ToLocalTime());
                        ConsoleFunctions.WriteDebugLine("Packet ID: " + Globals.v2Int32(message, 1)[0]);

                        PacketHandler.PacketHandler PH = new PacketHandler.PacketHandler();
                        Thread handler = new Thread(() => PH.HandlePacket(Client, message));
                        handler.Start();
                    }
                    if (bytesRead == 0)
                    {
                        //Close connection with user. as he disconnected!
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ConsoleFunctions.WriteErrorLine("ERROR! \n" + ex.Message);
                    break;
                }
            }
            ConsoleFunctions.WriteDebugLine("A client disconnected!");
            if (Utils.PlayerHelper.isConnectedPlayer(Client))
            {
                ConsoleFunctions.WriteInfoLine("Player '" + Utils.PlayerHelper.getPlayer(Client).Username + "' disconnected!");
                Client._Player.SaveToFile();
                Globals.Players.Remove(Utils.PlayerHelper.getPlayer(Client));
                Globals.PlayerOnline--;
                Globals.updateTitle();
            }
            tcpClient.Close();
            Globals.ActiveConnections--;
            Globals.updateTitle();
        }
Exemplo n.º 7
0
 public void ListenForClients()
 {
     Globals._ServerListener.Start();
     ConsoleFunctions.WriteServerLine("Ready for connections...");
     while (true)
     {
         TcpClient client = Globals._ServerListener.AcceptTcpClient();
         ConsoleFunctions.WriteDebugLine("A new connection has been made!");
         Globals.ActiveConnections++;
         Globals.updateTitle();
         Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientCommNew));
         clientThread.Start(client);
     }
 }
Exemplo n.º 8
0
        public void HandlePacket(object Client, byte[] Data)
        {
            ClientWrapper cWrapper = (ClientWrapper)Client;

            int[] _INT       = Globals.v2Int32(Data, 0);
            int   PacketSize = _INT[0];
            int   NextData   = _INT[1];

            ConsoleFunctions.WriteDebugLine("Packetsize: " + PacketSize.ToString() + " Next data: " + NextData.ToString());
            int PacketID = Globals.v2Int32(Data, NextData)[0];

            switch (PacketID)
            {
            case 0x00:
                new Handshake().Handle(cWrapper, Data);
                break;

            case 0x01:
                if (PacketSize == 9)
                {
                    new Ping().Handle(cWrapper, Data);
                }
                else
                {
                    new SharpMC.Networking.PacketHandler.Packets.Ingoing.ChatMessage().Handle(cWrapper, Data);
                }
                break;

            case 0x04:
                new PlayerPosition().Handle(cWrapper, Data);
                break;

            case 0x06:
                new PlayerPositionAndLook().Handle(cWrapper, Data);
                break;

            case 0x03:
                new SharpMC.Networking.PacketHandler.Packets.Ingoing.PlayerOnGround().Handle(cWrapper, Data);
                break;

            case 0x05:
                new SharpMC.Networking.PacketHandler.Packets.Ingoing.PlayerLook().Handle(cWrapper, Data);
                break;

            default:
                ConsoleFunctions.WriteWarningLine("Unknown packet received! ('" + PacketID + "')");
                break;
            }
        }
Exemplo n.º 9
0
 public dynamic GetProperty(string property, dynamic defaultValue)
 {
     foreach (string line in File.ReadAllLines(ConfigName))
     {
         string[] split = line.Split('=');
         if (split.Length >= 2)
         {
             if (!String.IsNullOrEmpty(split[0]) && split[0].Equals(property, StringComparison.InvariantCultureIgnoreCase))
             {
                 return(TypeDescriptor.GetConverter(defaultValue.GetType()).ConvertFromString(split[1]));
             }
         }
     }
     ConsoleFunctions.WriteDebugLine("Property value couldn't be found (Property: {0}, Value: {1})", true, property, defaultValue);
     return(defaultValue);
 }
Exemplo n.º 10
0
        public static int ReadVarInt(NetworkStream stream)
        {
            var value = 0;
            var size  = 0;
            int b;

            while (((b = stream.ReadByte()) & 0x80) == 0x80)
            {
                value |= (b & 0x7F) << (size++ *7);
                if (size > 5)
                {
                    ConsoleFunctions.WriteDebugLine("VarInt size is longer than expected. (Size: {0})", size);
                    //throw new IOException("VarInt size is longer than expected. (Size: {0})", size);
                }
            }
            return(value | ((b & 0x7F) << (size * 7)));
        }
Exemplo n.º 11
0
        public void ListenForClients()
        {
            var port = Config.GetProperty("port", 25565);

            if (port != 25565)
            {
                _serverListener = new TcpListener(IPAddress.Any, port);
            }

            _serverListener.Start();
            _listening = true;
            ConsoleFunctions.WriteServerLine("Ready for connections...");
            ConsoleFunctions.WriteInfoLine("To shutdown the server safely press CTRL+C");
            while (_listening)
            {
                var client = _serverListener.AcceptTcpClient();
                ConsoleFunctions.WriteDebugLine("A new connection has been made!");

                new Task((() => { HandleClientCommNew(client); })).Start();                 //Task instead of Thread
            }
        }
Exemplo n.º 12
0
        public CraftingRecipe(ItemStack result, object[] recipe)
        {
            resultItem = result;
            for (var i = 0; i < 3; i++)
            {
                if (recipe[i] is string)
                {
                    _recipe[i] = (string)recipe[i];
                }
                else
                {
                    throw new InvalidDataException("recipe invalid");
                }
            }

            var prevchar = ' ';

            for (var i = 4; i < recipe.Length; i++)             //Load dictionairy
            {
                var val = recipe[i];
                if (val is char)
                {
                    var d = (char)val;
                    prevchar = d;
                }

                if (val is ItemStack)
                {
                    var d = (ItemStack)val;
                    if (prevchar != ' ')
                    {
                        recipeDictionary.Add(prevchar, d);
                        prevchar = ' ';
                    }
                }
            }

            ConsoleFunctions.WriteDebugLine("Added crafting recipe for item id: " + result.ItemId);
        }
Exemplo n.º 13
0
        public static void SendResponse(ClientWrapper tcpClient, byte[] Data)
        {
            //   List<byte> actData = new List<byte>(Data[0] + 1);
            // for (int i = 0; i < (Data[0] + 1); i++)
            //{
            //   actData.Add(Data[i]);
            // }
            try
            {
                tcpClient.Client.NoDelay = false;
                NetworkStream clientStream = tcpClient.Client.GetStream();

                clientStream.Write(Data, 0, Data.Length);
                clientStream.Flush();
            }
            catch (Exception ex)
            {
                ConsoleFunctions.WriteErrorLine("F**K, We failed to send a packet... The following error occured: " + ex.Message);
            }
            ConsoleFunctions.WriteDebugLine("Packet send with Packet ID: " + Data[1]);
            ConsoleFunctions.WriteDebugLine("Packet send with Packet Length: " + Data[0]);
            ConsoleFunctions.WriteDebugLine("Actual packet length: " + Data.Length);
        }
Exemplo n.º 14
0
        public override void Handle(ClientWrapper Client, byte[] Data)
        {
            ClientWrapper tcpClient = Client;

            /*
             * I know Host and ActualPort are currently not used.
             * I will use them to verify people are not using a proxy later on.
             */
            int[] _Hostdata  = Globals.v2Int32(Data, 3);
            int   HostLength = _Hostdata[0];
            int   NextData   = _Hostdata[1];

            string Host = Encoding.UTF8.GetString(Data, NextData, HostLength);

            ushort actualPort;

            if (BitConverter.IsLittleEndian)
            {
                actualPort = BitConverter.ToUInt16(new byte[2] {
                    (byte)Data[14], (byte)Data[13]
                }, 0);
            }
            else
            {
                actualPort = BitConverter.ToUInt16(new byte[2] {
                    (byte)Data[13], (byte)Data[14]
                }, 0);
            }


            try
            {
                /*
                 * We get the Handshake state here.
                 * This way we know what we need to handle.
                 * If the handshake state is 1 then we know we have to handle a status request.
                 * If the handshake state is 2 then we know we have to handle a login request.
                 */
                int HandShakeState = Globals.v2Int32(Data, 15)[0];

                if (HandShakeState == 1)
                {
                    ConsoleFunctions.WriteDebugLine("Handling Status Request!");
                    StatusResponse(tcpClient, Data);
                }
                else if (HandShakeState == 2)
                {
                    ConsoleFunctions.WriteDebugLine("Handling Login Request!");
                    LoginRequest(tcpClient, Data);
                }
                else
                {
                    ConsoleFunctions.WriteDebugLine("We received an unknown Handshake state! WTF \nStopping");
                    return;
                }
            }
            catch (Exception ex)
            {
                /*
                 * Seems we have an error here.
                 * That's sad... We log it for debugging purposes.
                 */
                ConsoleFunctions.WriteDebugLine(ex.ToString());
            }
        }
Exemplo n.º 15
0
 public void AddLevel(string name, Level lvl)
 {
     ConsoleFunctions.WriteDebugLine("Initiating level: " + name);
     SubLevels.Add(name, lvl);
 }
Exemplo n.º 16
0
        /*
         * TODO: Fix data compression
         * TODO: Look into: Internal Exception: io.netty.handler.codec.DecoderException: java.lang.IndexOutOfBoundsException: readerIndex(2) + length(72) exceeds writerIndex(2): UnpooledHeapByteBuf(ridx: 2, widx: 2, cap: 2)
         */
        private void HandleClientConnection(TcpClient client)
        {
            NetworkStream clientStream  = client.GetStream();
            ClientWrapper WrappedClient = new ClientWrapper(client);

            Globals.ClientManager.AddClient(ref WrappedClient);
            while (true)
            {
                try
                {
                    if (Server.ServerSettings.UseCompression && WrappedClient.PacketMode == PacketMode.Play)
                    {
                        int packetLength     = NetUtils.ReadVarInt(clientStream);
                        int dataLength       = NetUtils.ReadVarInt(clientStream);
                        int actualDataLength = packetLength - NetUtils.GetVarIntBytes(dataLength).Length;
                        ConsoleFunctions.WriteInfoLine("PacketLength: {0} \n DataLength: {1} \n ActualDataLength: {2}", packetLength, dataLength, actualDataLength);
                        if (dataLength == 0)
                        {
                            if (!ReadCompressed(WrappedClient, clientStream, actualDataLength))
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (!ReadUncompressed(WrappedClient, clientStream, dataLength))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (!ReadUncompressed(WrappedClient, clientStream, NetUtils.ReadVarInt(clientStream)))
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ConsoleFunctions.WriteDebugLine("Error: \n" + ex);
                    if (Server.ServerSettings.ReportExceptionsToClient)
                    {
                        new Disconnect(WrappedClient)
                        {
                            Reason = new ChatText("Server threw an exception!\n\nException: \n" + ex.Message, TextColor.Reset)
                        }.Write();
                    }
                    else
                    {
                        new Disconnect(WrappedClient)
                        {
                            Reason = new ChatText("You were kicked because of an internal problem!", TextColor.Reset)
                        }.Write();
                    }
                    break;
                }
            }
            Globals.DisconnectClient(WrappedClient);
            Thread.CurrentThread.Abort();
        }
Exemplo n.º 17
0
        private bool ExecuteCommand(MethodInfo method, Player player, string[] args, CommandAttribute commandAttribute)
        {
            var parameters = method.GetParameters();

            var addLenght          = 0;
            int requiredParameters = 0;

            if (parameters.Length > 0 && parameters[0].ParameterType == typeof(Player))
            {
                addLenght          = 1;
                requiredParameters = -1;
            }

            bool hasRequiredParameters = true;
            bool hasStringArray        = false;

            foreach (var param in parameters)
            {
                if (!param.IsOptional)
                {
                    requiredParameters++;
                }
                if (param.ParameterType == typeof(string[]))
                {
                    hasStringArray = true;
                }
            }

            if (args.Length < requiredParameters && !hasStringArray)
            {
                hasRequiredParameters = false;
            }

            if (!hasRequiredParameters || args.Length > (parameters.Length - addLenght) && !hasStringArray)
            {
                player.SendChat("Invalid command usage!", ChatColor.Red);
                player.SendChat(commandAttribute.Usage, ChatColor.Red);
                return(true);
            }

            var objectArgs = new object[parameters.Length];

            bool          stringarrayfound    = false;
            int           stringarrayposition = 0;
            List <string> stringarrayvalues   = new List <string>();

            int length = args.Length + addLenght;

            for (var k = 0; k < length; k++)
            {
                var parameter = parameters[k];
                var i         = k - addLenght;
                if (k == 0 && addLenght == 1)
                {
                    if (parameter.ParameterType == typeof(Player))
                    {
                        objectArgs[k] = player;
                        continue;
                    }
                    ConsoleFunctions.WriteWarningLine("Command method " + method.Name + " missing Player as first argument.");
                    return(false);
                }

                if (parameter.ParameterType == typeof(string[]))
                {
                    stringarrayfound    = true;
                    stringarrayposition = k;
                    stringarrayvalues.Add(args[i]);

                    objectArgs[stringarrayposition] = stringarrayvalues.ToArray();
                    break;
                }

                if (parameter.ParameterType == typeof(string))
                {
                    objectArgs[k] = args[i];
                    continue;
                }

                if (parameter.ParameterType == typeof(byte))
                {
                    byte value;
                    if (!byte.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(short))
                {
                    short value;
                    if (!short.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(int))
                {
                    int value;
                    if (!int.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(bool))
                {
                    bool value;
                    if (!bool.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(float))
                {
                    float value;
                    if (!float.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(double))
                {
                    double value;
                    if (!double.TryParse(args[i], out value))
                    {
                        return(false);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                if (parameter.ParameterType == typeof(Player))
                {
                    Player value = Globals.LevelManager.GetAllPlayers().FirstOrDefault(p => p.Username.ToLower().Equals(args[i].ToLower()));
                    if (value == null)
                    {
                        player.SendChat(String.Format("Player \"{0}\" is not found!", args[i]), ChatColor.Red);
                        return(true);
                    }
                    objectArgs[k] = value;
                    continue;
                }

                return(false);
            }

            if (stringarrayfound)
            {
                for (int k = stringarrayposition + 1; k <= args.Length; k++)
                {
                    var i = k - addLenght;
                    stringarrayvalues.Add(args[i]);
                    objectArgs[stringarrayposition] = stringarrayvalues.ToArray();
                }
            }

            var pluginInstance = _plugins.FirstOrDefault(plugin => plugin.GetType() == method.DeclaringType);

            if (pluginInstance == null)
            {
                ConsoleFunctions.WriteDebugLine("Plugin instance is null!");
                return(false);
            }

            if (method.IsStatic)
            {
                method.Invoke(null, objectArgs);
            }
            else
            {
                if (method.DeclaringType == null)
                {
                    return(false);
                }

                method.Invoke(pluginInstance, objectArgs);
            }

            return(true);
        }
Exemplo n.º 18
0
        private void HandleClientCommNew(object client)
        {
            var tcpClient    = (TcpClient)client;
            var clientStream = tcpClient.GetStream();
            var Client       = new ClientWrapper(tcpClient);

            Globals.ClientManager.AddClient(ref Client);

            while (true)
            {
                try
                {
                    while (!clientStream.DataAvailable)
                    {
                        if (Client.Kicked)
                        {
                            break;
                        }
                        Thread.Sleep(5);
                    }

                    if (Client.Kicked)
                    {
                        break;
                    }

                    if (ServerSettings.UseCompression && Client.PacketMode == PacketMode.Play)
                    {
                        int packetLength     = ReadVarInt(clientStream);
                        int dataLength       = ReadVarInt(clientStream);
                        int actualDataLength = packetLength - GetVarIntBytes(dataLength).Length;

                        if (dataLength == 0)
                        {
                            if (!ReadCompressed(Client, clientStream, actualDataLength))
                            {
                                break;
                            }
                        }
                        else
                        {
                            if (!ReadUncompressed(Client, clientStream, dataLength))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        int dlength = ReadVarInt(clientStream);
                        if (!ReadUncompressed(Client, clientStream, dlength))
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Exception, disconnect!
                    ConsoleFunctions.WriteDebugLine("Error: \n" + ex);
                    if (ServerSettings.ReportExceptionsToClient)
                    {
                        new Disconnect(Client)
                        {
                            Reason = new McChatMessage("§fServer threw an exception!\n\nFor the nerdy people: \n" + ex.Message)
                        }.Write();
                    }
                    else
                    {
                        new Disconnect(Client)
                        {
                            Reason = new McChatMessage("§fYou were kicked because of an unknown problem!")
                        }.Write();
                    }
                    break;
                }
            }

            if (Client.Kicked)
            {
                new Disconnect(Client)
                {
                    Reason = new McChatMessage("§fYou were kicked because of a network problem!")
                }.Write();
            }

            //Close the connection with the client. :)
            Client.ThreadPool.KillAllThreads();
            //Client.StopKeepAliveTimer();

            if (Client.Player != null)
            {
                Client.Player.SavePlayer();
                Client.Player.Level.RemovePlayer(Client.Player.EntityId);
                Client.Player.Level.BroadcastPlayerRemoval(Client);
            }

            Client.TcpClient.Close();
            Globals.ClientManager.RemoveClient(Client);
            Thread.CurrentThread.Abort();
        }
Exemplo n.º 19
0
        private void LoginRequest(ClientWrapper tcpClient, byte[] Data)
        {
            /*
             * We need to get the username another way than Hardcode it in...
             * I don't see where to get it from at the moment tho :S
             */

            /*
             *  Oops this code below was published accidentaly!
             *  I was checking for a way i can retrieve the username. Still seems bugged tho, really strange.
             */
            int[] UsernameStuff   = Globals.v2Int32(Data, 3);
            int   _UsernameLength = UsernameStuff[0];
            int   NextIndex       = UsernameStuff[1];

            ConsoleFunctions.WriteDebugLine("Username length: " + _UsernameLength + " | Next index: " + NextIndex);
            string uName = Encoding.UTF8.GetString(Data, NextIndex, _UsernameLength);

            ConsoleFunctions.WriteDebugLine("Username: "******"kennyvv";

            byte[] _Username = Encoding.UTF8.GetBytes(Username);

            //We grab the UUID for the Username.
            string UUID = Globals.getUUID(Username);
            Guid   g    = new Guid(UUID);

            UUID = g.ToString();
            byte[] _UUID      = Encoding.UTF8.GetBytes(UUID);
            byte[] PacketID   = Globals.getVarInt(0x02);
            byte[] UUIDLength = Globals.getVarInt(_UUID.Length);
            Player _Player;

            //We create new player data.
            //This is the data we can retrieve later on using the PlayerHelper class.
            try
            {
                try
                {
                    _Player = Utils.PlayerHelper.getPlayer(UUID);
                }
                catch (FileNotFoundException ex)
                {
                    _Player = SharpMC.Utils.PlayerHelper.addPlayer(new Player()
                    {
                        Username = Username, UUID = UUID, Gamemode = new Gamemode()
                        {
                            _Gamemode = 1
                        }, Position = new Position()
                        {
                            X = 0, Y = 0, Z = 50
                        }, Client = tcpClient
                    });
                }
                _Player.Client = tcpClient;
                _Player.SaveToFile();
                tcpClient._Player = _Player;
            }
            catch (NotSupportedException ex)
            {
                //Seems we already added this user after all. WTF?!
                //Then why didn't we find it? :O
            }


            byte[] UsernameLength = Globals.getVarInt(_Username.Length);
            byte[] TotalLength    = Globals.getVarInt(PacketID.Length + _UUID.Length + _Username.Length + UUIDLength.Length + UsernameLength.Length);

            byte[] Response = Globals.concatBytes(TotalLength, PacketID, UUIDLength, _UUID, UsernameLength, _Username);
            Network.SendResponse(tcpClient, Response);

            //We send all packets needed for the player to spawn in the game.
            //We still need to send the chunks here.
            //However our world generation class is currently not done.
            CompressionLevel(tcpClient, Data);
            PlayResponse(tcpClient, Data);
            SpawnPositionResponse(tcpClient, Data);
            new Outgoing.PlayerAbilities().Handle(tcpClient, Data);
            new Outgoing.PlayerPositionAndLook().Handle(tcpClient, Data);
        }
Exemplo n.º 20
0
 public override void Handle(ClientWrapper Client, byte[] Data)
 {
     ConsoleFunctions.WriteDebugLine("Handling PING Request!");
     Network.SendResponse(Client, Data);
 }
Exemplo n.º 21
0
        private void HandleClientCommNew(object client)
        {
            var tcpClient    = (TcpClient)client;
            var clientStream = tcpClient.GetStream();
            var Client       = new ClientWrapper(tcpClient);

            while (true)
            {
                try
                {
                    var buffie = new byte[4096];
                    int receivedData;
                    receivedData = clientStream.Read(buffie, 0, buffie.Length);

                    if (receivedData > 0)
                    {
                        var buf = new MSGBuffer(Client);

                        if (Client.Decrypter != null)
                        {
                            var date = new byte[4096];
                            Client.Decrypter.TransformBlock(buffie, 0, buffie.Length, date, 0);
                            buf.BufferedData = date;
                        }
                        else
                        {
                            buf.BufferedData = buffie;
                        }

                        buf.BufferedData = buffie;

                        var length = buf.ReadVarInt();
                        buf.Size = length;
                        var packid = buf.ReadVarInt();

                        if (!new PackageFactory(Client, buf).Handle(packid))
                        {
                            ConsoleFunctions.WriteWarningLine("Unknown packet received! \"0x" + packid.ToString("X2") + "\"");
                        }
                        buf.Dispose();
                    }
                    else
                    {
                        //Stop the while loop. Client disconnected!
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Client.ThreadPool.KillAllThreads();
                    //Exception, disconnect!
                    ConsoleFunctions.WriteDebugLine("Error: \n" + ex);
                    new Disconnect(Client)
                    {
                        Reason = "§4SharpMC\n§fServer threw an exception!\n\nFor the nerdy people: \n" + ex.Message
                    }.Write();
                    break;
                }
            }
            //Close the connection with the client. :)
            Client.ThreadPool.KillAllThreads();
            Client.StopKeepAliveTimer();

            if (Client.Player != null)
            {
                Client.Player.Level.RemovePlayer(Client.Player);
                Client.Player.Level.BroadcastPlayerRemoval(Client);
            }
            Client.TcpClient.Close();
            Thread.CurrentThread.Abort();
        }