Пример #1
0
        public string ReadString()
        {
            byte[] readString = new byte[1024];
            byte   c;
            int    charCount = 0;

            // Read from the stream until \0 is read
            while ((c = reader.ReadByte()) != 0x00)
            {
                try {
                    readString[charCount] = c;
                    charCount++;
                } catch (ArgumentOutOfRangeException) {
                    ServerConsole.WriteLine(System.Drawing.Color.Red, "Received string was longer than 1024 byte!");
                    break;
                }
            }

            string returnString;

            try {
                returnString = Encoding.ASCII.GetString(readString, 0, charCount);
            } catch (Exception) {
                ServerConsole.WriteLine(System.Drawing.Color.Red, "There was an error while converting data to a string!");
                returnString = " ";
            }

            return(returnString);
        }
Пример #2
0
        /// <summary>
        /// Process Client connections, and calls a Async Callback
        /// </summary>
        private static void ProcessConnections()
        {
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Server.PORT);
            Socket     listener      = new Socket(
                AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp
                );

            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(5);

                while (Server.Running)
                {
                    resetEvent.Reset();
                    listener.BeginAccept(new AsyncCallback(Server.CallbackAccept), listener);
                    resetEvent.WaitOne();
                }
            }
            catch (Exception e)
            {
                ServerConsole.WriteLine(System.Drawing.Color.Red, e.ToString());
            }
        }
Пример #3
0
        /// <summary>
        /// Callback that handles client connections
        /// </summary>
        /// <param name="ar"></param>
        private static void CallbackAccept(IAsyncResult ar)
        {
            resetEvent.Set();

            ///
            /// Listen for connections
            ///
            Socket listener = (Socket)ar.AsyncState;
            Socket handler  = listener.EndAccept(ar);

            ///
            /// Client connected ! Creating client object.
            ///
            Client client = new Client(handler);

            clients.Add(client);
            ServerConsole.WriteLine(Color.Blue, "Client #{0} connected from {1}", client.IP);

            ///
            /// Starts to listen for client input
            ///
            handler.BeginReceive(
                client.Buffer, 0,
                Client.BUFFERSIZE, 0,
                new AsyncCallback(client.OnReceive),
                null
                );
        }
Пример #4
0
        /// <summary>
        /// Handles client disconnecting
        /// </summary>
        public void Disconnect()
        {
            if (user != null)
            {
                Server.Users.Remove(user.UserId);
                MainForm.Instance.InvokeDelegate(delegate() {
                    MainForm.Instance.usersListBox.Items.Remove(user.Username);
                });
                ServerConsole.WriteLine(Color.Blue, "Connection for client #{0} terminated.", user.UserId);
            }

            if (mainSocket.Connected)
            {
                mainSocket.Shutdown(SocketShutdown.Both);
            }

            mainSocket.Close();
            mainSocket = null;

            try {
                World.FreeId(character.WorldID);
            } catch (Exception) {}

            if (character != null)
            {
                SaveCharacterLocation();
            }

            Server.ClientDisconnected(this);
        }
Пример #5
0
 public void Request(byte skillId, uint playerId)
 {
     if (!Handlers.ContainsKey(skillId))
     {
         ServerConsole.WriteLine(System.Drawing.Color.Red, "Unknown Skill Id #{0}", skillId);
     }
 }
Пример #6
0
        public static void DumpUnknown(PacketIn packet)
        {
            ServerConsole.Write(System.Drawing.Color.Red, "Dumping unknown packet with Id {0:X2}: ", packet.PacketType);

            for (int i = 0; i < (packet.PacketSize - 3); i++)
            {
                ServerConsole.Write(System.Drawing.Color.Red, "{0} ", packet.ReadByte());
            }

            ServerConsole.WriteLine("");
        }
Пример #7
0
        public static void DumpUnusedPacket(string name, PacketIn packet)
        {
            ServerConsole.Write(System.Drawing.Color.Red, "Dumping unused packet #{0} with Id {1:X2}: ", name, packet.PacketType);

            for (int i = 0; i < (packet.PacketSize - 3); i++)
            {
                ServerConsole.Write(System.Drawing.Color.Red, "{0} ", packet.ReadByte());
            }

            ServerConsole.WriteLine("");
        }
Пример #8
0
        /// <summary>
        /// Loads all the maps.
        /// </summary>
        public static void LoadMaps()
        {
            _maps = new Map[50, 50];
            using (XmlTextReader xtr = new XmlTextReader("Maps.xml"))
            {
                done = true;
                string mapName;
                int    posX;
                int    posY;

                while (xtr.Read())
                {
                    if (xtr.NodeType == XmlNodeType.Element)
                    {
                        if (xtr.Name == "Map")
                        {
                            mapName = xtr.GetAttribute("Src");
                            Utils.XmlNextElement(xtr);

                            if (xtr.Name == "Position")
                            {
                                try
                                {
                                    posX = Int32.Parse(xtr.GetAttribute("PosX"));
                                    posY = Int32.Parse(xtr.GetAttribute("PosY"));
                                    _maps[posX, posY] = new Map(mapName);
                                }
                                catch (FormatException)
                                {
                                    ServerConsole.WriteLine(
                                        System.Drawing.Color.Red,
                                        "Invalid position encountered while loading maps. [{0}]",
                                        xtr.LineNumber);
                                    done = false;
                                }
                                catch (FileNotFoundException)
                                {
                                    ServerConsole.WriteLine(
                                        System.Drawing.Color.Red,
                                        "An error was encountered while loading a map. [{0}]",
                                        xtr.LineNumber);
                                    done = false;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Starts a Kalonline Server, with following actions
        /// - Configure NHibernate (ORM)
        /// - Load Maps
        /// - Start ClientHandling thread
        /// </summary>
        public Server()
        {
            ///
            /// Load Server Config
            ///
            if (File.Exists("Config.xml"))
            {
                XPathNavigator config = new XPathDocument("Config.xml").CreateNavigator();
                PORT = Int32.Parse(config.SelectSingleNode("config/port").Value);
            }
            else
            {
                ServerConsole.WriteLine(Color.Red, "Could not find Config.xml, aborting startup.");
                return;
            }

            ///
            /// Configure NHibernate
            ///
            ServerConsole.WriteLine(Color.Blue, "- [Configuring Database]");
            Configuration cfg = new Configuration();

            cfg.AddAssembly("Emulator");
            Factory = cfg.BuildSessionFactory();

            ///
            /// Load Maps
            ///
            ServerConsole.WriteLine(Color.Blue, "- [Loading Maps]");
            World.LoadMaps();

            ///
            /// Load NPCs
            ///
            ServerConsole.WriteLine(Color.Blue, "- [Loading NPCs]");
            World.LoadNPCs();

            if (World.done)
            {
                ///
                /// Start the server
                ///
                processConnectionsThread = new Thread(
                    new ThreadStart(Server.ProcessConnections)
                    );
                processConnectionsThread.Start();
                ServerThinker.Start();
                ServerConsole.WriteLine("Server Started");
            }
        }
Пример #10
0
        /// <summary>
        /// Handles packet receiving
        /// </summary>
        /// <param name="result"></param>
        public void OnReceive(IAsyncResult result)
        {
            try
            {
                int bytesRead = mainSocket.EndReceive(result);
                if (bytesRead > 0)
                {
                    Array.Copy(_buffer, 0, tempBuffer, tempSize, bytesRead);
                    tempSize += bytesRead;
                }
                else
                {
                    Disconnect();
                    return;
                }
            }
            catch (SocketException e)
            {
                if (e.ErrorCode == 10054)
                {
                    Disconnect();
                    return;
                }
                ServerConsole.WriteLine(Color.Red, "Socket Error: {0}", e.Message);
                return;
            } catch (ObjectDisposedException) {
            } catch (NullReferenceException) {
            }

            while (tempSize >= 2 && tempSize >= ((int)tempBuffer[0] + (((int)tempBuffer[1]) << 8)))
            {
                int chunkSize = (int)tempBuffer[0] + (((int)tempBuffer[1]) << 8);

                Process(tempBuffer);

                Array.Copy(tempBuffer, chunkSize, tempBuffer, 0, tempSize - chunkSize);
                tempSize -= chunkSize;
            }

            try {
                mainSocket.BeginReceive(_buffer, 0, BUFFERSIZE, 0, new AsyncCallback(OnReceive), null);
            } catch (Exception) {}
        }
Пример #11
0
        /// <summary>
        /// Executes the thoughts work
        /// </summary>
        public void Work()
        {
            while (true)
            {
                int time = _time;

                Thought head;
                Thought pos;
                pos  = head = _head;
                head = _head = Thought.UnlinkJob(_head, time);
                if (pos == head)
                {
                    Thread.Sleep(10);
                    continue;
                }

                while (pos != null)
                {
                    Thought next = pos.Next;
                    pos.Unlink(null);

                    try {
                        pos.Trigger();
                    } catch (Exception e) {
                        ServerConsole.WriteLine(System.Drawing.Color.Red, "Exception in timed callback: {0}", e.Message);
                        if (e.StackTrace != null)
                        {
                            ServerConsole.WriteLine(System.Drawing.Color.Red, e.StackTrace);
                        }
                        ServerConsole.WriteLine("");
                    }
                    pos = next;
                }
                _time = Math.Min(_time, time + 5);
                Thread.Sleep(10);
            }
        }
Пример #12
0
        /// <summary>
        /// Creates a Character
        /// </summary>
        /// <param name="name">Character Name</param>
        /// <param name="classId">Class</param>
        /// <param name="strength">Strength</param>
        /// <param name="health">Health</param>
        /// <param name="intelligence">Intelligence</param>
        /// <param name="wisdom">Wisdom</param>
        /// <param name="agility">Agility</param>
        /// <param name="face">Face Style</param>
        /// <param name="hair">Hair Style</param>
        public int CreateCharacter(string name, byte classId, byte strength, byte health, byte intelligence,
                                   byte wisdom, byte agility, byte face, byte hair)
        {
            ServerConsole.WriteLine("Creating character called {0} for {1}.", name, user.Username);

            ///
            /// Configure the stats correctly foreach class
            ///
            switch (classId)
            {
            case 0:
                strength     += 18;
                health       += 16;
                intelligence += 8;
                wisdom       += 8;
                agility      += 10;
                break;

            case 1:
                strength     += 8;
                health       += 10;
                intelligence += 18;
                wisdom       += 16;
                agility      += 8;
                break;

            case 2:
                strength     += 14;
                health       += 10;
                intelligence += 8;
                wisdom       += 10;
                agility      += 18;
                break;
            }

            ///
            /// Add random extra stats
            ///
            for (int i = 0; i < 5; i++)
            {
                switch (Server.ServerRandom.Next(0, 4))
                {
                case 0: strength += 1; break;

                case 1: health += 1; break;

                case 2: intelligence += 1; break;

                case 3: wisdom += 1; break;

                case 4: agility += 1; break;
                }
            }

            ///
            /// Character Creation
            ///
            Player p;

            using (session = Server.Factory.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    ///
                    /// Create Player
                    ///
                    p              = new Player();
                    p.UserId       = user.UserId;
                    p.Status       = 1;
                    p.Name         = name;
                    p.ClassId      = (int)classId;
                    p.Level        = 1;
                    p.Job          = 0;
                    p.Strength     = (int)strength;
                    p.Health       = (int)health;
                    p.Intelligence = (int)intelligence;
                    p.Wisdom       = (int)wisdom;
                    p.Agility      = (int)agility;
                    p.Face         = (int)face;
                    p.Hair         = (int)hair;
                    p.X            = 257491;
                    p.Y            = 258584;
                    p.Z            = 16120;

                    session.Save(p);
                    transaction.Commit();
                }

            return(p.PlayerId);
        }