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("Received string was longer than 1024 byte!"); break; } } string returnString; try { returnString = Encoding.ASCII.GetString(readString, 0, charCount); } catch (Exception) { ServerConsole.WriteLine("There was an error while converting data to a string!"); returnString = " "; } return(returnString); }
public void Start() { //database Database.Connect(); //hackshiedl Hackshield.Load(); //get path to config files string configPath = Path.Combine(Environment.CurrentDirectory, Settings.Default.ConfigPath); //load config files ConfigManager.LoadConfigFiles(configPath); //read config files ConfigManager.ReadConfig(); //load item codes Configs.Items.ItemCodes.CodeManager.Load(); //load chat manager Chat.ChatManager.Load(); //prepare a new world ServerWorld.Load(2); //start server ProcessConnectionsThread = new Thread( new ThreadStart(Server.ProcessConnections) ); ProcessConnectionsThread.Start(); Thinker.Start(); ServerConsole.WriteLine("Server started on port {0}", MessageLevel.Message, Settings.Default.Port); }
public static void Connect() { ServerConsole.WriteLine("Database connecting...", MessageLevel.ODBC); //create config ServerConsole.WriteLine("Connecting to KalAuth...", MessageLevel.ODBC); Configuration cfg = new Configuration().Configure("kalauth.cfg.xml"); //load resources ServerConsole.WriteLine("Loading resources", MessageLevel.ODBC); cfg.AddResource(@"KalSharp.Account.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly()); //building config KalAuth = cfg.BuildSessionFactory(); ServerConsole.WriteLine("Connected to KalAuth", MessageLevel.ODBC); //create config ServerConsole.WriteLine("Connecting to KalDB...", MessageLevel.ODBC); Configuration cfg2 = new Configuration().Configure("kaldb.cfg.xml"); //load resources ServerConsole.WriteLine("Loading resources", MessageLevel.ODBC); cfg2.AddResource(@"KalSharp.Player.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly()); cfg2.AddResource(@"KalSharp.PlayerDeleted.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly()); cfg2.AddResource(@"KalSharp.Worlds.Items.Item.hbm.xml", System.Reflection.Assembly.GetExecutingAssembly()); //building config KalDB = cfg2.BuildSessionFactory(); ServerConsole.WriteLine("Connected to KalDB", MessageLevel.ODBC); }
/// <summary> /// Handles client disconnecting /// </summary> public void Close() { if (Account != null) { ServerConsole.WriteLine("Connection for client #{0} terminated.", MessageLevel.Message, Account.ID); } else { ServerConsole.WriteLine("Unknown client disconnected"); } if (Character != null) { UnspawnPlayer(); } if (Socket.Connected) { Socket.Shutdown(SocketShutdown.Both); } Socket.Close(); Socket = null; //free world id try { UnspawnPlayer(); } catch (Exception) { } Server.RemoveClient(this); }
/// <summary> /// Process Client connections, and calls a Async Callback /// </summary> private static void ProcessConnections() { IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Settings.Default.Port); Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); try { listener.Bind(localEndPoint); listener.Listen(5); while (Running) { ResetEvent.Reset(); listener.BeginAccept(new AsyncCallback(CallbackAccept), listener); ResetEvent.WaitOne(); } } catch (Exception e) { ServerConsole.WriteLine("Socket error: {0} at {1}", MessageLevel.Error, e.Message, e.TargetSite.Name); } }
/// <summary> /// Process a packet input /// </summary> /// <param name="buffer"></param> public void Process(byte[] buffer) { try { PacketIn packet = new PacketIn(buffer, packetKey); handler.Translate(this, packet.PacketType, packet); if (packet.PacketType == 0xA3) { ServerConsole.WriteLine("0xa3 packet type"); return; } if (packetKey == 63) { packetKey = 0; } else { packetKey++; } } catch (Exception ex) { ServerConsole.WriteLine("Packet Error: {0}", MessageLevel.Error, ex.Message, ex.TargetSite.Name); } }
/// <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); Thinker.Add(5, new DelegateThought.ThoughtCallback(Test), client); ServerConsole.WriteLine("Client #{0} connected from {1}", MessageLevel.Warning, Clients.Count, client.IP); /// /// Starts to listen for client input /// handler.BeginReceive( client.Buffer, 0, Client.BUFFERSIZE, 0, new AsyncCallback(client.OnReceive), null ); }
public static void DumpUnusedPacket(string name, PacketIn packet) { ServerConsole.WriteLine("Dumping unused packet #{0} with Id {1:X2}: ", MessageLevel.Warning, name, packet.PacketType); for (int i = 0; i < (packet.PacketSize - 3); i++) { ServerConsole.WriteLine("{0} ", MessageLevel.Warning, packet.ReadByte()); } ServerConsole.WriteLine(""); }
public static void DumpUnknown(PacketIn packet) { ServerConsole.WriteLine("Dumping unknown packet with Id {0:X2}: ", MessageLevel.Warning, packet.PacketType); for (int i = 0; i < (packet.PacketSize - 3); i++) { ServerConsole.WriteLine("{0} ", MessageLevel.Warning, packet.ReadByte()); } ServerConsole.WriteLine(""); }
public static void Load() { ServerConsole.WriteLine("Hackshield Initializing", MessageLevel.Hackshield); suspicionList = new Dictionary <OffenseSeverity, int>(); suspicionList.Add(OffenseSeverity.IncorrectPacketDetails, 50); suspicionList.Add(OffenseSeverity.OutOfPlacePacket, 100); suspicionList.Add(OffenseSeverity.CooldownHacking, 25); suspicionList.Add(OffenseSeverity.SpeedHacking, 25); suspicionList.Add(OffenseSeverity.UndergroundHacking, 25); }
/// <summary> /// Handles packet receiving /// </summary> /// <param name="result"></param> public void OnReceive(IAsyncResult result) { try { int bytesRead = Socket.EndReceive(result); if (bytesRead > 0) { Array.Copy(_buffer, 0, tempBuffer, tempSize, bytesRead); tempSize += bytesRead; } else { Close(); return; } } catch (SocketException e) { if (e.ErrorCode == 10054) { Close(); return; } ServerConsole.WriteLine("Socket Error: {0}", MessageLevel.Error, e.Message); return; } catch (ObjectDisposedException e) { ServerConsole.WriteLine("Object Disposed Error: {0}", MessageLevel.Error, e.Message); } catch (NullReferenceException e) { ServerConsole.WriteLine("Null Error: {0}", MessageLevel.Error, e.Message); } 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 { Socket.BeginReceive(_buffer, 0, BUFFERSIZE, 0, new AsyncCallback(OnReceive), null); } catch (Exception) { } }
public void Translate(Client client, byte packetId, PacketIn packet) { if (!Handlers.ContainsKey(packetId)) { ServerConsole.WriteLine("Unknown Packet Detected.", MessageLevel.Warning); PacketTranslator.DumpUnknown(client, packet); } else { try { Handlers[packetId](client, packet); } catch (Exception ex) { ServerConsole.WriteLine("Translator Error: {0} for packet {1}", MessageLevel.Error, ex.ToString(), packetId); } } }
/// <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("Exception in timed callback: {0}", MessageLevel.Error, e.Message); if (e.StackTrace != null) { ServerConsole.WriteLine(e.StackTrace, MessageLevel.Error); } ServerConsole.WriteLine(""); } pos = next; } _time = Math.Min(_time, time + 5); Thread.Sleep(10); } }
public void DeletePlayer(int PID) { ServerConsole.WriteLine("Deleteing player {0}", MessageLevel.Message, PID); Player p = Player.GetPlayer(PID); //set uid to 0 to show player deleted. p.UID = 0; Database.Update(Database.KalDB, p); using (session = Database.KalDB.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { PlayerDeleted pd = new PlayerDeleted(); pd.PID = PID; pd.UID = Account.UID; pd.DeletedTime = DateTime.Now; session.Save(pd); transaction.Commit(); } } }
static void Main(string[] args) { try { ServerConsole.PrintLogo(); int i = 0; while (i < 80) { Console.Write("-"); //Thread.Sleep(20); i++; } ServerConsole.WriteLine("Server Starting", MessageLevel.Message); Server server = new Server(); server.Start(); Console.Read(); } catch (Exception ex) { ServerConsole.WriteLine(ex.ToString(), MessageLevel.Fatal); } Console.ReadKey(); }
/// <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 CreatePlayer(string Name, int Class, int Strength, int Health, int Intelligence, int Wisdom, int Dexterity, int Face, int Hair) { ServerConsole.WriteLine("Creating character called {0} for {1}.", MessageLevel.Message, Name, Account.ID); /// /// Configure the stats correctly foreach class /// switch (Class) { case 0: Strength += 18; Health += 16; Intelligence += 8; Wisdom += 8; Dexterity += 10; break; case 1: Strength += 8; Health += 10; Intelligence += 18; Wisdom += 16; Dexterity += 8; break; case 2: Strength += 14; Health += 10; Intelligence += 8; Wisdom += 10; Dexterity += 18; break; } //create player Player p; using (session = Database.KalDB.OpenSession()) { using (ITransaction transaction = session.BeginTransaction()) { p = new Player(); p.UID = Account.UID; p.Name = Name; p.Class = (byte)Class; p.Level = 1; p.Specialty = 0; p.Strength = (byte)Strength; p.Health = (byte)Health; p.Intelligence = (byte)Intelligence; p.Wisdom = (byte)Wisdom; p.Dexterity = (byte)Dexterity; p.Face = (byte)Face; p.Hair = (byte)Hair; p.X = 257491; p.Y = 258584; p.Z = 16120; session.Save(p); transaction.Commit(); } } return(p.PID); }
public void Send(PacketOut packet, string title) { ServerConsole.WriteLine("Sending [{0}]", MessageLevel.Message, title); this.Send(packet); }