public NetManager()
 {
     NetPeerConfiguration config = new NetPeerConfiguration("Jape.Moose");
     config.Port = 10900;
     config.LocalAddress = NetUtility.Resolve("localhost");
     m_server = new NetServer(config);
 }
Beispiel #2
0
 public void UpdateAllResources(NetServer server)
 {
     foreach (Player item in this.Players)
     {
         this.UpdateResource(server, item);
     }
 }
Beispiel #3
0
        public Server()
        {
            ConnectedPlayers = new List<ConnectedPlayer>();

            _configuration = new NetPeerConfiguration("space_fight");
            server = new NetServer(_configuration);
        }
Beispiel #4
0
        public static void Process(NetServer server, NetBuffer buffer, NetConnection sender)
        {
            Config config = Config.Instance;

            List<NetConnection> connections = server.Connections;

            //Lets send that message onto any plugin clients
            foreach (NetConnection connection in connections)
            {
                if (config.Server.client_connections.ContainsKey(connection.RemoteEndpoint.ToString()))
                {
                    string client_type = (string)config.Server.client_connections[connection.RemoteEndpoint.ToString()];

                    if (client_type.ToLower() == "plugin")
                    {
                        string msg = buffer.ReadString();

                        Console.WriteLine("Slave: Data sent - " + msg);

                        NetBuffer slavebuf = server.CreateBuffer();

                        slavebuf.Write(msg);

                        server.SendMessage(slavebuf, connection, NetChannel.ReliableInOrder4);
                    }
                }
            }
        }
Beispiel #5
0
 public Server(int MaxConnections, int Port)
 {
     NetPeerConfiguration config = new NetPeerConfiguration("CozyAnywhere");
     config.MaximumConnections   = MaxConnections;
     config.Port                 = Port;
     server                      = new NetServer(config);
 }
Beispiel #6
0
 public NetworkManager(int Port, string AppID)
 {
     Config = new NetPeerConfiguration(AppID);
     Config.Port = Port;
     Server = new NetServer(Config);
     Server.Start();
 }
Beispiel #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetworkServer" /> class.
 /// </summary>
 /// <param name="applicationIdentifier">The application identifier.</param>
 /// <param name="port">The port.</param>
 public NetworkServer(string applicationIdentifier, int port)
 {
     var config = new NetPeerConfiguration(applicationIdentifier);
     config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
     config.Port = port;
     this.server = new NetServer(config);
 }
Beispiel #8
0
        static void Main(string[] args)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            Console.WriteLine("This is the server");
            Players = new List<Player>();
            Config = new NetPeerConfiguration("MyGame");
            Console.WriteLine("Server configuration created.");
            Config.Port = 7777;
            Config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            Server = new NetServer(Config);
            Console.WriteLine("Server socket initialized");
            Server.RegisterReceivedCallback(new SendOrPostCallback(ReceiveData));
            Server.Start();
            Console.WriteLine("Server started");

            new Thread(new ThreadStart(delegate
                {
                    string input;

                    while ((input = Console.ReadLine()) != null)
                    {
                        Console.WriteLine("New Input.");
                        string[] prms = input.Split(' ');

                        switch (prms[0])
                        {
                            //No commands on server as of now
                        }
                    }
                })).Start();
        }
        public void SetUpConnection()
        {
            configuration = new NetPeerConfiguration("PingPong");

            configuration.EnableMessageType(NetIncomingMessageType.WarningMessage);
            configuration.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            configuration.EnableMessageType(NetIncomingMessageType.ErrorMessage);
            configuration.EnableMessageType(NetIncomingMessageType.Error);
            configuration.EnableMessageType(NetIncomingMessageType.DebugMessage);
            configuration.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            configuration.EnableMessageType(NetIncomingMessageType.Data);

            switch (networkRole)
            {
                case GamerNetworkType.Client:
                    Client = new NetClient(configuration);
                    Client.Start();
                    Client.Connect(new IPEndPoint(NetUtility.Resolve(IP), Convert.ToInt32(Port)));
                    break;
                case GamerNetworkType.Server:
                    configuration.Port = Convert.ToInt32(Port);
                    Server = new NetServer(configuration);
                    Server.Start();
                    break;
                default:
                    throw new ArgumentException("Network type was not set");
            }
        }
Beispiel #10
0
        private static void HandleMessage(NetIncomingMessage inc, NetServer server)
        {
            switch (inc.MessageType)
            {
                case NetIncomingMessageType.ConnectionApproval: //If ConnectionApproval request
                    if (inc.ReadByte() == (byte) PacketTypes.Headers.Login)
                    {
                        string username = inc.ReadString();
                        Console.WriteLine("New Login Request from: {0}", username);
                        if (username.Length > 1 & Players.Values.All(c => c.Name != username) &
                            !_badwordList.Contains(username, StringComparer.OrdinalIgnoreCase))
                        {
                            inc.SenderConnection.Approve();
                            NetOutgoingMessage connectedMessage = server.CreateMessage();
                            Thread.Sleep(500);
                            Console.WriteLine("Sending a ack to {0}", username);
                            connectedMessage.Write((byte) PacketTypes.Headers.LoggedIn);
                            connectedMessage.Write(true);
                            server.SendMessage(connectedMessage, inc.SenderConnection, NetDeliveryMethod.ReliableOrdered);
                        }
                        else
                        {
                            inc.SenderConnection.Deny("Bad Username");
                        }
                    }

                    break;

                case NetIncomingMessageType.Data:
                    byte packetheader = inc.ReadByte();
                    HandleProtocol(inc, packetheader, server);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    Console.WriteLine(inc.SenderConnection + " status changed. " + inc.SenderConnection.Status);
                    if (inc.SenderConnection.Status == NetConnectionStatus.Disconnected)
                    {
                        Console.WriteLine("Player: {0} has disconnected",
                            Players[inc.SenderConnection.RemoteUniqueIdentifier].Name);
                        Players.Remove(inc.SenderConnection.RemoteUniqueIdentifier);
                    }
                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    NetOutgoingMessage discovermsg = server.CreateMessage();
                    discovermsg.Write("Hey I just met you, I'm a server, so address me maybe");
                    Console.WriteLine(@"Auto Discovery Request");
                    server.SendDiscoveryResponse(discovermsg, inc.SenderEndPoint);
                    break;

                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    Console.WriteLine(@"---Debug---");
                    Console.WriteLine(inc.ReadString());
                    Console.WriteLine(@"---End---");
                    break;
            }
        }
 public Server_Model2()
 {
     _netconfig = new NetPeerConfiguration("SkyNet") { Port = 9000 };
     _server = new NetServer(_netconfig);
     _assembly = new SuperAssembly("Server");
     _thread = new Thread(Thread);
 }
Beispiel #12
0
 public TrackingServer(int port, string applicationName)
 {
   NetPeerConfiguration config = new NetPeerConfiguration(applicationName);
   config.Port = port;
   netServer = new NetServer(config);
   Console.WriteLine("Server " + applicationName + " started succesfully");
 }
Beispiel #13
0
        /// <summary>
        /// Default constructor for the WizardryGameServer class.
        /// </summary>
        public WizardryGameServer()
        {
            graphics = new GraphicsDeviceManager( this );
            Content.RootDirectory = "Content";
            textureProvider = new TextureProvider( Content );

            // Windows Settings for the XNA window
            Window.Title = "Wizardry Server";
            graphics.PreferredBackBufferWidth = 200;
            graphics.PreferredBackBufferHeight = 1;

            // Set up the lobbies list
            lobbies = new GameLobby[GameSettings.MAX_LOBBIES];
            for ( int i = 0; i < GameSettings.MAX_LOBBIES; ++i )
            {
                lobbies[i] = null;
            }

            playerLobbies = new ConcurrentDictionary<long, int>();

            // Setup the server configuration
            NetPeerConfiguration config = new NetPeerConfiguration( GameSettings.APP_NAME );
            config.Port = GameSettings.SERVER_PORT_NUM;
            config.EnableMessageType( NetIncomingMessageType.DiscoveryRequest );

            // Start the server
            server = new NetServer( config );
            server.Start();
            WriteConsoleMessage( "Server starting!" );

            // Start the Packet Receiver thread
            Thread packets = new Thread( new ThreadStart( this.PacketProcessor ) );
            packets.Start();
        }
Beispiel #14
0
        public void SetupServer(string gameName, int port = 14242, int maxConnections = 20)
        {
            // Create new instance of configs. Parameter is "application Id". It has to be same on client and server.
            var config = new NetPeerConfiguration(gameName) { Port = port, MaximumConnections = maxConnections };
            _heroList = new List<LoginInfo>();
            // Set server port

            // Max client amount
            // Enable New messagetype. Explained later
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            // Create new server based on the configs just defined
            _gameServer = new NetServer(config);

            // Start it
            _gameServer.Start();

            // Eh..
            Console.WriteLine("Server Started");

            // Object that can be used to store and read messages
            NetIncomingMessage inc;
            _serverThread = new Thread(() =>
            {
                while (true)
                {
                    ServerLoop();
                }
            });
            _serverThread.IsBackground = true;
            _serverThread.Start();
        }
        /// <summary>
        ///     Server constructor, starts the server and connects to all region servers.
        /// </summary>
        /// <remarks>
        ///     TODO: Make the config file be able to be in a different location. Load from command line.
        /// </remarks>
        public MasterServer()
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(MasterConfig));
            MasterConfig masterconfig = (MasterConfig)deserializer.Deserialize(XmlReader.Create(@"C:\Users\Addie\Programming\Mobius\Mobius.Server.MasterServer\bin\Release\MasterData.xml"));
            //Start it with the name MobiusMasterServer, and let connection approvals be enabled
            var config = new NetPeerConfiguration(masterconfig.ServerName);
            config.Port = masterconfig.ServerPort;
            config.MaximumConnections = masterconfig.MaxConnections;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            LidgrenServer = new NetServer(config);

            RegionServers = new Dictionary<ushort, NetClient>();
            foreach(RegionInfo info in masterconfig.RegionServers)
            {
                NetClient region = new NetClient(new NetPeerConfiguration(info.ServerName));
                region.Start();
                region.Connect(info.ServerIp, info.ServerPort);
                RegionServers.Add(info.RegionId, region);
            }

            //Initialize our data structures
            Users = new Dictionary<Guid, User>();
            UserIdToCharacters = new Dictionary<Guid, List<Character>>();
            //Start the server
            LidgrenServer.Start();
        }
Beispiel #16
0
        public GameServer()
        {
            /* Load Resources */
            Console.WriteLine("Loading Resources...");
            Resources = new ResourceManager();
            Resources.Load();

            /* Setting Up Server */
            Console.WriteLine("Starting Up Server...");
            //Package.RecompilePackages();
            //CodeManager StartUp = Package.GetPackage(Game.ServerInfo.StartupPackage).CodeManager;
            //StartUp.RunMain();
            //Game.World.Chunks.ClearWorldGen();
            //Game.World.Chunks.AddWorldGens(StartUp.GetWorldGens());
            Game.World.ClearWorldGen();
            List<WorldGenerator> temp = new List<WorldGenerator>();
            temp.Add(new WorldGenerator());
            Game.World.AddWorldGen(temp);

            /* Listen for Clients */
            NetPeerConfiguration Configuration = new NetPeerConfiguration("FantasyScape");
            Configuration.Port = 54987;
            Configuration.MaximumConnections = 20;
            Server = new NetServer(Configuration);
            Server.Start();
            Message.RegisterServer(Server);

            UpdateTimer = new Stopwatch();
            UpdateTimer.Start();

            Console.WriteLine("Ready!");
        }
Beispiel #17
0
 private static void SendMessage(NetServer server, MsgBase msg, NetConnection conn)
 {
     NetOutgoingMessage om = server.CreateMessage();
     om.Write(msg.Id);
     msg.W(om);
     server.SendMessage(om, conn, NetDeliveryMethod.Unreliable, 0);
 }
Beispiel #18
0
 private static void SendMessage(NetServer server, MsgBase msg)
 {
     NetOutgoingMessage om = server.CreateMessage();
     om.Write(msg.Id);
     msg.W(om);
     server.SendToAll(om, NetDeliveryMethod.Unreliable);
 }
Beispiel #19
0
        private static bool ProcessPacket(NetServer server, int id, NetIncomingMessage msg)
        {
            if (id == MsgId.AccountReg)
            {
                OnProcessAccountReg(server, id, msg);
                return true;
            }
            else if (id == MsgId.AgarLogin)
            {
                OnProcessLogin(server, id, msg);
                return true;
            }
            else if (id == MsgId.AgarPlayInfo)
            {
                return OnProcessPlayerInfo(server, id, msg);
            }
            else if (id == MsgId.AgarBorn)
            {
                OnProcessBorn(server, id, msg);
                return true;
            }
            else if (id == MsgId.HappyPlayerLogin)
            {
                OnProcessHappyLogin(server, id, msg);
                return true;
            }
            else if(id == MsgId.HappyPlayerMove)
            {
                return OnProgressHappyPlayerMove(server, id, msg);
            }

            return false;
        }
Beispiel #20
0
        /// <summary>
        ///     Метод для работып отока обработчика входящих новых соединений с сервером
        /// </summary>
        private static void ServerHandleConnections(object obj) {
            Log.Print("Starting Listen connections", LogType.Network);

            var config = new NetPeerConfiguration(Settings.GameIdentifier) {
                Port = Settings.Port,
                MaximumConnections = Settings.MaxConnections,
                SendBufferSize = 400000,
                UseMessageRecycling = true,
            };

            /* Получаем возможные адреса сервера */
            Log.Print("Server IP's:", LogType.Network);
            Log.Print("-------", LogType.Network);
            IPAddress[] ipList = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in ipList) {
                if (ip.AddressFamily == AddressFamily.InterNetwork) {
                    Log.Print(ip.ToString(), LogType.Network);
                }
            }
            Log.Print("-------", LogType.Network);

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

            // Запускаем обработчик пакетов
            StartProcessIncomingMessages();
        }
Beispiel #21
0
 public void fireClientApproval(NetServer server, NetBuffer buffer, NetConnection sender)
 {
     if (ClientApproval != null)
     {
         ClientApproval(server, buffer, sender);
     }
 }
Beispiel #22
0
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			MainForm = new Form1();

			NetPeerConfiguration config = new NetPeerConfiguration("durable");
			config.Port = 14242;
			config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
			config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
			config.EnableUPnP = true;
			Server = new NetServer(config);
			Server.Start();

			// attempt upnp port forwarding
			Server.UPnP.ForwardPort(14242, "Durable sample test");

			m_expectedReliableOrdered = new uint[3];
			m_reliableOrderedCorrect = new int[3];
			m_reliableOrderedErrors = new int[3];

			m_expectedSequenced = new uint[3];
			m_sequencedCorrect = new int[3];
			m_sequencedErrors = new int[3];

			Application.Idle += new EventHandler(AppLoop);
			Application.Run(MainForm);

			Server.Shutdown("App exiting");
		}
Beispiel #23
0
        public Boolean Open()
        {
            var result = true;

            if (nethandler == null || netaddress == null || netport == 0 || netmax == 0)
            {
                result = false;
            }
            else
            {
                if (netconn == null)
                {
                    netconfig      = new NetPeerConfiguration("AuthServer");
                    netconfig.Port = netport;
                    netconfig.MaximumConnections = netmax;
                    netconn = new Lidgren.Network.NetServer(netconfig);
                    netconn.RegisterReceivedCallback(new SendOrPostCallback(nethandler), new SynchronizationContext());
                }
                try {
                    netconn.Start();
                    result = true;
                } catch {
                    result = false;
                }
            }
            return(result);
        }
        /// <summary>
        ///     Constructor taking the path to the configuration file. 
        ///     Starts the lidgren server to start listening for connections, and 
        ///     initializes all data structres and such.
        /// </summary>
        /// <param name="configpath"></param>
        public RegionServer(string configpath)
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(RegionConfig));
            RegionConfig regionconfig = (RegionConfig)deserializer.Deserialize(XmlReader.Create(configpath));

            //Create the server
            var config = new NetPeerConfiguration(regionconfig.ServerName);
            config.Port = regionconfig.ServerPort;
            LidgrenServer = new NetServer(config);
            LidgrenServer.Start();

            //Initizlie our data structures
            Characters = new Dictionary<Guid, Character>();
            UserIdToMasterServer = new Dictionary<Guid, NetConnection>();
            TeleportEnters = new List<TeleportEnter>(regionconfig.TeleportEnters);
            TeleportExits = new List<TeleportExit>(regionconfig.TeleportExits);
            ItemSpawns = new List<ItemSpawn>(regionconfig.ItemSpawns);
            ItemSpawnIdGenerator = new UniqueId();
            ItemSpawnsWaitingForSpawn = new Dictionary<ItemSpawn, DateTime>();

            foreach(ItemSpawn spawn in ItemSpawns)
                ItemSpawnIdGenerator.RegisterId(spawn.Id);

            RegionId = regionconfig.RegionId;
        }
Beispiel #25
0
 public void fireStatusChanged(NetServer server, NetBuffer buffer, NetConnection sender)
 {
     if (StatusChanged != null)
     {
         StatusChanged(server, buffer, sender);
     }
 }
Beispiel #26
0
 public void fireDataRecieved(NetServer server, NetBuffer buffer, NetConnection sender)
 {
     if (DataRecieved != null)
     {
         DataRecieved(server, buffer, sender);
     }
 }
Beispiel #27
0
 public void StatusCallbackImpl(NetServer server, NetIncomingMessage msg)
 {
     NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();
     if (status == NetConnectionStatus.Disconnected)
     {
         RemoveFarmObj(msg.SenderConnection);
     }
 }
Beispiel #28
0
 protected override void OnInitialise()
 {
     Log.Info(String.Format("Initialising NetServer on Port {0}..", _config.Port));
     OnIncomingMessage += LidgrenServer_OnIncomingMessage;
     _config.AcceptIncomingConnections = true;
     _server = new NetServer(_config);
     _server.Start();
 }
Beispiel #29
0
 public Server(ManagerLogger managerLogger)
 {
     _managerLogger = managerLogger;
     _gameRooms = new List<GameRoom>();
     _config = new NetPeerConfiguration("networkGame") { Port = 14241 };
     _config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
     NetServer = new NetServer(_config);
 }
 public ServerNetworkManager(NetServer netServer)
 {
     this.netServer = netServer;
     imh = new ServerIncomingMessageHandler(netServer, IncomingMessageQueue);
     omh = new ServerOutgoingMessageHandler(netServer, OutgoingMessageQueue);
     IncomingMessageHandlerThread = new Thread(imh.run);
     IncomingMessageHandlerThread.Start();
 }
 public ServerContinuousSynchronizer(GameState game, NetServer server, PlayerConnectionLookup connections)
     : base(game)
 {
     this.server = server;
     this.connections = connections;
     this.timeToNextObjectUpdate = TimeSpan.One;
     this.timeToNextEcoUpdate = TimeSpan.One;
 }
Beispiel #32
0
        public void AddListener(ushort port, int maxClient)
        {
            var config = new NetPeerConfiguration(SharedUtil.GetAppIdentifierForNet());

            config.Port = port;
            config.MaximumConnections = maxClient;
            //config.DualStack = true;

            _netServer = new Lidgren.Network.NetServer(config);
            _netServer.Start();
        }
        /// <summary>
        /// Approves the connection and sents/sends local hail data provided
        /// </summary>
        public void Approve(byte[] localHailData)
        {
            if (m_approved == true)
            {
                throw new NetException("Connection is already approved!");
            }

            //
            // Continue connection phase
            //

            if (localHailData != null)
            {
                m_localHailData = localHailData;
            }

            // Add connection
            m_approved = true;

            NetServer server = m_owner as NetServer;

            server.AddConnection(NetTime.Now, this);
        }
Beispiel #34
0
        static void Main(string[] args)
        {
            var config = new NetPeerConfiguration("ConquerLeague")
            {
                Port = 47410
            };

            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            server = new NetServer(config);
            server.Start();

            SessionManager sessionManager = new SessionManager();

            while (true)
            {
                NetIncomingMessage message;
                while ((message = server.ReadMessage()) != null)
                {
                    switch (message.MessageType)
                    {
                    case NetIncomingMessageType.DiscoveryRequest:
                        NetOutgoingMessage response = server.CreateMessage();           // Create a response and write some example data to it
                        response.Write("ConquerLeagueServer");
                        server.SendDiscoveryResponse(response, message.SenderEndPoint); // Send the response to the sender of the request
                        break;

                    case NetIncomingMessageType.Data:
                        var dataLength = message.ReadInt32();
                        var data       = message.ReadBytes(dataLength);
                        sessionManager.ForwardMessageToSession(message.SenderConnection, dataLength, data);
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        Console.WriteLine(message.SenderConnection.Status);
                        switch (message.SenderConnection.Status)
                        {
                        case NetConnectionStatus.Connected:
                            Console.WriteLine("Client " + message.SenderConnection.RemoteEndPoint.ToString() + " connected!");
                            sessionManager.AddPlayerToMatchmaking(message.SenderConnection);
                            break;

                        case NetConnectionStatus.RespondedConnect:
                            Console.WriteLine(message.SenderConnection.Status.ToString());
                            break;

                        default:
                            Console.WriteLine("Unhandled status change with type: " + message.SenderConnection.Status.ToString());
                            break;
                        }

                        break;

                    case NetIncomingMessageType.ConnectionApproval:
                        message.SenderConnection.Approve();
                        break;

                    case NetIncomingMessageType.DebugMessage:
                        Console.WriteLine(message.ReadString());
                        break;

                    case NetIncomingMessageType.WarningMessage:
                        Console.WriteLine("Warning: " + message.ReadString());
                        break;

                    default:
                        Console.WriteLine("unhandled message with type: " + message.MessageType);
                        break;
                    }

                    server.Recycle(message);
                }
            }
        }