Ejemplo n.º 1
0
        public Game()
        {
            Console.WriteLine("Game");

            connections = new Dictionary <int, Player>();
            rooms       = new Dictionary <int, List <NetConnection> >();

            peerConfiguration = new NetPeerConfiguration(appIdentifier)
            {
                MaximumConnections = 128,
                Port = port
            };

            server = new NetServer(peerConfiguration);
            server.Start();
        }
Ejemplo n.º 2
0
        public void StartServer()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("chat");

            config.Port = 14242;
            server      = new NetServer(config);
            server.Start();

            if (server.Status == NetPeerStatus.Running)
            {
                Console.WriteLine("Server is running on port " + config.Port);
            }
            else
            {
                Console.WriteLine("Server not started...");
            }
            clients = new List <NetPeer>();
        }
Ejemplo n.º 3
0
        public void Start()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MulTUNG");

            config.Port         = (int)Configuration.Get <long>("ServerPort", 5678);
            config.LocalAddress = IPAddress.Parse(Configuration.Get("LocalServerIP", "127.0.0.1"));
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            Server = new NetServer(config);
            Server.Start();

            Network.IsServer = true;

            ThreadPool.QueueUserWorkItem(_ =>
            {
                NetIncomingMessage msg;
                while (Server != null)
                {
                    msg = Server.WaitMessage(int.MaxValue);

                    if (msg == null)
                    {
                        continue;
                    }

                    HandleMessage(msg);

                    Server.Recycle(msg);
                }
            });

            World.AddNetObjects();
            World.LoadCircuitState();

            Network.StartPositionUpdateThread(Constants.PositionUpdateInterval);

            Log.WriteLine("Listening on port " + config.Port);
        }
        void Init(uint16_t inPort, byte worldCount, float ConnectionTimeout)
        {
            base.Init(worldCount);
            mNewNetworkId = new ushort[worldCount];
            mNewPlayerId  = new int[worldCount];
            for (byte i = 0; i < worldCount; ++i)
            {
                ResetNewNetworkId(i);
                mNewPlayerId[i] = 1;
            }

            NetPeerConfiguration config = new NetPeerConfiguration("game");

            config.MaximumConnections = 1000;
            config.Port = inPort;
            config.ConnectionTimeout = ConnectionTimeout;
            mNetPeer = new NetServer(config);
            mNetPeer.Start();

            algo = new NetXorEncryption(GetServer(), "AceTopSecret");

            // tcp
            SetListener(inPort);
        }
Ejemplo n.º 5
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            ParseArguments(args);

            SetupConsoleLogging();

            m_Thread = Thread.CurrentThread;
            Process  = Process.GetCurrentProcess();
            Assembly = Assembly.GetEntryAssembly();

            if (m_Thread != null)
            {
                m_Thread.Name = "Core Thread";
            }

            if (BaseDirectory.Length > 0)
            {
                Directory.SetCurrentDirectory(BaseDirectory);
            }

            var version = Assembly.GetName().Version;

            CoreVersion = version;

            var platform = (int)Environment.OSVersion.Platform;

            if (platform == 4 || platform == 128)
            {
                Unix = true;
            }

            GCSettings.LatencyMode = GCLatencyMode.LowLatency;

            log.Info("X-RunUO Server - Version {0}.{1}.{2}, Build {3}", version.Major, version.Minor, version.Build, version.Revision);
            log.Info("Running on OS {0}", Environment.OSVersion);
            log.Info("Running on {0} {1}", Unix ? "Mono" : ".NET Framework", Environment.Version);

            if (MultiProcessor || Is64Bit)
            {
                log.Info("Optimizing for {0} {2}processor{1}", ProcessorCount, ProcessorCount == 1 ? "" : "s", Is64Bit ? "64-bit " : "");
            }

            log.Info("Using GC {0} {1} mode", GCSettings.IsServerGC ? "Server" : "Workstation", GCSettings.LatencyMode);

            Config = new RootConfig(BaseDirectory, "x-runuo.xml");

            Server.Config.Load();

            #region Dependency management
            LibraryConfig = new LibraryConfig(BaseDirectory, "libraries.xml");

            if (ForceUpdateDeps)
            {
                Directory.Delete(Path.Combine(BaseDirectory, "deps"), recursive: true);
            }
            #endregion

            if (!ScriptCompiler.Compile(Debug))
            {
                log.Fatal("Compilation failed. Press any key to exit.");
                Console.ReadLine();
                return;
            }

            ScriptCompiler.VerifyLibraries();

            // This instance is shared among timer scheduler and timer executor,
            // and accessed from both core & timer threads.
            var timerQueue = new Queue <Timer>();

            // Timer scheduler must be set up before world load, since world load
            // could schedule timers on entity deserialization.
            var timerScheduler = TimerScheduler.Instance = new TimerScheduler(timerQueue);
            m_TimerThread = new TimerThread(timerScheduler);

            var timerExecutor = new TimerExecutor(timerQueue);

            try
            {
                ScriptCompiler.Configure();

                TileData.Configure();
            }
            catch (TargetInvocationException e)
            {
                log.Fatal("Configure exception: {0}", e.InnerException);
                return;
            }

            SaveConfig();

            Region.Load();
            World.Load();

            try
            {
                ScriptCompiler.Initialize();
            }
            catch (TargetInvocationException e)
            {
                log.Fatal("Initialize exception: {0}", e.InnerException);
                return;
            }

            m_TimerThread.Start();

            NetServer netServer = new NetServer(new Listener(Listener.Port));
            netServer.Initialize();

            GameServer.Instance = new GameServer(netServer);
            GameServer.Instance.Initialize();

            EventSink.InvokeServerStarted();

            PacketDispatcher.Initialize();

            Now              = DateTime.UtcNow;
            m_TotalProfile   = new MainProfile(Now);
            m_CurrentProfile = new MainProfile(Now);

            try
            {
                while (!Closing)
                {
                    Now = DateTime.UtcNow;

                    Thread.Sleep(1);

                    ClockProfile(MainProfile.TimerId.Idle);

                    Mobile.ProcessDeltaQueue();

                    ClockProfile(MainProfile.TimerId.MobileDelta);

                    Item.ProcessDeltaQueue();

                    ClockProfile(MainProfile.TimerId.ItemDelta);

                    timerExecutor.Slice();

                    ClockProfile(MainProfile.TimerId.Timers);

                    netServer.Slice();

                    ClockProfile(MainProfile.TimerId.Network);

                    // Done with this iteration.
                    m_TotalProfile.Next();
                    m_CurrentProfile.Next();
                }
            }
            catch (Exception e)
            {
                HandleCrashed(e);
            }

            m_TimerThread.Stop();
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            bool verbose = true;

            // Prepare crypto
            RandomProvider provider = new RegularRandomProvider();
            RSA            func     = LoadRSA(provider);

            if (func == null)
            {
                func = GenerateRSA();
            }

            Console.WriteLine("Server starting!\nType \"help\" for a list of serverside commands");

            XmlDocument doc = new XmlDocument();

            try { doc.Load(db); } // Attempt to load the xml document
            catch (Exception)
            {
                // If the xml-document doesn't exist, start building one
                XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(declaration);
            }


            // Create a server with the given RSA function
            NetServer server = new NetServer(func, port, (string message, out bool keepAlive) =>
            {
                if (verbose)
                {
                    Console.WriteLine("Got message from client: " + message);
                }
                keepAlive = true;

                // Check if the message sent was a "Store" command
                if (message.StartsWith("S-") && message.Substring(2).Contains("-"))
                {
                    // Split up the message into its relevant parts: Sender and Message
                    string data = message.Substring(2);
                    string auth = data.Substring(0, data.IndexOf('-'));
                    string msg  = data.Substring(data.IndexOf('-') + 1);

                    // Look up some stuff
                    XmlNodeList lst_u = doc.SelectNodes("users");
                    XmlElement users;
                    if (lst_u.Count == 0)
                    {
                        users = doc.CreateElement("users");
                        doc.AppendChild(users);
                    }
                    else
                    {
                        users = (XmlElement)lst_u.Item(0);
                    }

                    XmlElement userSet = null;
                    foreach (var child in users.ChildNodes)
                    {
                        if (child is XmlElement && ((XmlElement)child).Name.Equals("U" + auth))
                        {
                            userSet = (XmlElement)child;
                            break;
                        }
                    }

                    // If a node doesn't exist for the user, create it
                    if (userSet == null)
                    {
                        userSet = doc.CreateElement("U" + auth);
                        users.AppendChild(userSet);
                    }

                    // Store the message and save
                    XmlElement messageNode = doc.CreateElement("msg");
                    messageNode.InnerText  = msg;
                    userSet.AppendChild(messageNode);

                    if (verbose)
                    {
                        Console.WriteLine("Saving document...");
                    }
                    doc.Save(db);
                }
                // Check if the message was a "Load" command
                else if (message.StartsWith("L-"))
                {
                    // Get the authentication code
                    string auth = message.Substring(2);

                    // Load some xml stuff
                    XmlNode users = doc.SelectSingleNode("users");

                    XmlNodeList elements = null;
                    foreach (var user in users.ChildNodes)
                    {
                        if (user is XmlElement && ((XmlElement)user).Name.Equals("U" + auth))
                        {
                            elements = ((XmlElement)user).ChildNodes;
                            break;
                        }
                    }

                    // There are no stored messages for the given auth. code: respond with a blank message
                    if (elements == null)
                    {
                        return("M-");
                    }

                    if (elements.Count != 0)
                    {
                        List <string> collect = new List <string>();
                        foreach (var element in elements)
                        {
                            if (element is XmlElement)
                            {
                                collect.Add(((XmlElement)element).InnerText);
                            }
                        }

                        // Respond with all the elements (conveniently serialized)
                        return("M-" + Support.SerializeStrings(collect.ToArray()));
                    }
                }

                // No response
                return(null);
            },
                                             client =>
            {
                // Notify the console of the new client
                if (verbose)
                {
                    Console.WriteLine($"Client has connected: {client.ToString()}");
                }
            });

            server.StartListening();

            // Server terminal command loop
            while (server.Running)
            {
                string s = Console.ReadLine().ToLower();
                if (s.Equals("help"))
                {
                    Console.WriteLine("Available commands:\n\tcount\t\t-\tShow active client count\n\tstop\t\t-\tStop server\n\ttv\t\t-\tToggle server verbosity\n\tsv\t\t-\tDisplay current server verbosity setting");
                }
                else if (s.Equals("count"))
                {
                    Console.WriteLine("Active client count: " + server.Count);
                }
                else if (s.Equals("stop"))
                {
                    Console.WriteLine("Stopping server...");
                    server.StopRunning();
                }
                else if (s.Equals("tv"))
                {
                    Console.WriteLine("Set verbosity to: " + (verbose = !verbose));
                }
                else if (s.Equals("sv"))
                {
                    Console.WriteLine("Current server verbosity: " + verbose);
                }
            }
        }
Ejemplo n.º 7
0
        public static void Run()
        {
            EventSink.Instance = new EventSink();

            if (!ScriptCompiler.Compile(Environment.Debug))
            {
                Console.WriteLine("Fatal: Compilation failed. Press any key to exit.");
                Console.ReadLine();
                return;
            }

            ScriptCompiler.VerifyLibraries();

            // This instance is shared among timer scheduler and timer executor,
            // and accessed from both core & timer threads.
            Queue <Timer> timerQueue = new Queue <Timer>();

            // Timer scheduler must be set up before world load, since world load
            // could schedule timers on entity deserialization.
            var timerScheduler = TimerScheduler.Instance = new TimerScheduler(timerQueue);

            m_TimerThread = new TimerThread(timerScheduler);

            TimerExecutor timerExecutor = new TimerExecutor(timerQueue);

            PacketHandlers.Instance = new PacketHandlers();

            try
            {
                ScriptCompiler.Configure();

                TileData.Configure();
            }
            catch (TargetInvocationException e)
            {
                Console.WriteLine("Fatal: Configure exception: {0}", e.InnerException);
                return;
            }

            Environment.SaveConfig();

            Region.Load();
            World.Instance.Load();

            try
            {
                ScriptCompiler.Initialize();
            }
            catch (TargetInvocationException e)
            {
                Logger.Error("Initialize exception: {0}", e.InnerException);
                return;
            }

            m_TimerThread.Start();

            NetServer netServer = new NetServer(new Listener(Listener.Port));

            netServer.Initialize();

            GameServer.Instance = new GameServer(netServer, PacketHandlers.Instance);
            GameServer.Instance.Initialize();

            EventSink.Instance.InvokeServerStarted();

            PacketDispatcher.Initialize();

            m_Now            = DateTime.UtcNow;
            m_TotalProfile   = new MainProfile(m_Now);
            m_CurrentProfile = new MainProfile(m_Now);

            try
            {
                while (!m_Closing)
                {
                    m_Now = DateTime.UtcNow;

                    Thread.Sleep(1);

                    ClockProfile(MainProfile.TimerId.Idle);

                    Mobile.ProcessDeltaQueue();

                    ClockProfile(MainProfile.TimerId.MobileDelta);

                    Item.ProcessDeltaQueue();

                    ClockProfile(MainProfile.TimerId.ItemDelta);

                    timerExecutor.Slice();

                    ClockProfile(MainProfile.TimerId.Timers);

                    netServer.Slice();

                    ClockProfile(MainProfile.TimerId.Network);

                    // Done with this iteration.
                    m_TotalProfile.Next();
                    m_CurrentProfile.Next();
                }
            }
            catch (Exception e)
            {
                HandleCrashed(e);
            }

            m_TimerThread.Stop();
        }
Ejemplo n.º 8
0
 public Server(string apiUrl)
 {
     _apiUrl    = apiUrl;
     _netServer = new NetServer();
     _players   = new Dictionary <long, Player>();
 }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            var config = new NetPeerConfiguration("application name")
            {
                Port = 12345
            };
            var server = new NetServer(config);

            server.Start();

            // server

            NetIncomingMessage msg;

            GameRoom newGameRoom = new GameRoom(null, "TEST", 8);

            NetworkSessionContainer.NetworkSessions.GameRooms.Add(newGameRoom);


            while (true)
            {
                //Ustawić odświerzanie co 16.666ms
                foreach (GameRoom gameRoom in NetworkSessionContainer.NetworkSessions.GameRooms)
                {
                    gameRoom.Update();
                }

                if ((msg = server.ReadMessage()) == null)
                {
                    continue;
                }


                switch (msg.MessageType)
                {
                case NetIncomingMessageType.ConnectionApproval:
                {
                    Console.WriteLine("Connected");
                    break;
                }

                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.StatusChanged:
                {
                    NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
                    break;
                }

                case NetIncomingMessageType.Data:
                {
                    short opcode = msg.ReadInt16();
                    if (opcode == 2000)      //Logowanie użytkownika
                    {
                        unsafe
                        {
                            if (!NetworkSessionContainer.NetworkSessions.UserSessions.Exists(x => x.Connection == msg.SenderConnection))
                            {
                                UserSession    session = new UserSession();
                                TypedReference tr      = __makeref(session);
                                IntPtr         ptr     = **(IntPtr **)(&tr);
                                Console.WriteLine(ptr);
                                session.Connection = msg.SenderConnection;
                                Random randID = new Random();
                                session.ID = randID.Next(1000000);         //martwić sie tym będe później
                                //session.ID = ptr.ToInt32();
                                session.Name = msg.ReadString();

                                NetOutgoingMessage outMessage = session.Connection.Peer.CreateMessage();
                                outMessage.Write((short)2000);
                                outMessage.Write(session.ID);
                                session.Connection.SendMessage(outMessage, NetDeliveryMethod.UnreliableSequenced,
                                                               outMessage.LengthBytes);
                                session.UserGameState = new MenuState();
                                NetworkSessionContainer.NetworkSessions.UserSessions.Add(session);
                                // Musze dorobić jakąś obsługe menu
                            }
                            else
                            {
                                //Zaimplementować że jest już taki gość
                            }

                            //TO NIE SPAWN A LOGIN

                            /*foreach (UserSession otherPlayers in UsersSessions.Sessions)
                             * {
                             *  NetOutgoingMessage informAboutPlayer = session.Connection.Peer.CreateMessage();
                             *  informAboutPlayer.Write((short)2620);
                             *  informAboutPlayer.Write(otherPlayers.ID, 32);
                             *  informAboutPlayer.Write("konserwa");
                             *  session.Connection.SendMessage(informAboutPlayer, NetDeliveryMethod.UnreliableSequenced, informAboutPlayer.LengthBytes);
                             *  Console.WriteLine($"Wysyłam pakiet od {session.ID} wysyłam dane o {otherPlayers.ID}");
                             *  //Console.WriteLine(BitConverter.ToString(informAboutPlayer.Data));
                             *
                             *
                             *  NetOutgoingMessage SendToCurrentPlayerAboutPlayers = otherPlayers.Connection.Peer.CreateMessage();
                             *  SendToCurrentPlayerAboutPlayers.Write((short)2620);
                             *  SendToCurrentPlayerAboutPlayers.Write(session.ID, 32);
                             *  SendToCurrentPlayerAboutPlayers.Write("konserwa");
                             *  otherPlayers.Connection.SendMessage(SendToCurrentPlayerAboutPlayers, NetDeliveryMethod.UnreliableSequenced, SendToCurrentPlayerAboutPlayers.LengthBytes);
                             *  Console.WriteLine($"Wysyłam pakiet od {otherPlayers.ID} wysyłam dane o {session.ID}");
                             * //  Console.WriteLine(BitConverter.ToString(SendToCurrentPlayerAboutPlayers.Data));
                             * }*/
                        }
                    }
                    else
                    {
                        //     NetworkSessionContainer.NetworkSessions.UserSessions.Find(x => x.Connection == msg.SenderConnection).UserGameState.Recive(msg);
                        foreach (UserSession user in NetworkSessionContainer.NetworkSessions.UserSessions)
                        {
                            if (user.Connection == msg.SenderConnection)
                            {
                                user.UserGameState.Recive(msg);
                            }
                        }
                    }



                    break;
                }

                case NetIncomingMessageType.ErrorMessage:
                    Console.WriteLine(msg.ReadString());
                    break;

                default:
                {
                    Console.WriteLine("Unhandled type: " + msg.MessageType);
                    break;
                }
                }

                //server.Recycle(msg);
            }
        }