Example #1
0
        public MyMultiplayerPeers()
        {
            IPAddress mask;

            m_localIp = NetUtility.GetMyAddress(out mask);

            m_netConfig      = new NetPeerConfiguration(MyMwcNetworkingConstants.NETWORKING_MULTIPLAYER_ID);
            m_netConfig.Port = MyMwcNetworkingConstants.NETWORKING_PORT_MULTIPLAYER_PEER;
            m_netConfig.AcceptIncomingConnections = true;
            m_netConfig.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
            m_netConfig.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true); // For NAT punch
            m_netConfig.MaximumTransmissionUnit = 1350;                                      // just to be sure
            if (MyFakes.MULTIPLAYER_LONG_TIMEOUT)
            {
                m_netConfig.PingInterval      = 60 * 10 - 2;
                m_netConfig.ConnectionTimeout = 60 * 10;
            }

// Because of lidgren
#if DEBUG
            if (MyFakes.MULTIPLAYER_SIMULATE_LAGS)
            {
                m_netConfig.SimulatedMinimumLatency   = 0.1f;  // 100ms minimum lag
                m_netConfig.SimulatedRandomLatency    = 0.2f;  // +/-200ms lag
                m_netConfig.SimulatedLoss             = 0.05f; // 5% loss
                m_netConfig.SimulatedDuplicatesChance = 0.03f; // 3% duplicates
            }
#endif
        }
Example #2
0
        private NetPeerConfiguration _getBaseNetPeerConfig()
        {
            var netConfig = new NetPeerConfiguration("SS14_NetTag");

            // ping the client once per second.
            netConfig.PingInterval = 1f;

            netConfig.SendBufferSize           = _config.GetCVar(CVars.NetSendBufferSize);
            netConfig.ReceiveBufferSize        = _config.GetCVar(CVars.NetReceiveBufferSize);
            netConfig.MaximumHandshakeAttempts = 5;

            var verbose = _config.GetCVar(CVars.NetVerbose);

            netConfig.SetMessageTypeEnabled(NetIncomingMessageType.VerboseDebugMessage, verbose);

            if (IsServer)
            {
                netConfig.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
                netConfig.MaximumConnections = _config.GetCVar(CVars.GameMaxPlayers);
            }


#if DEBUG
            //Simulate Latency
            netConfig.SimulatedLoss             = _config.GetCVar <float>("net.fakeloss");
            netConfig.SimulatedMinimumLatency   = _config.GetCVar <float>("net.fakelagmin");
            netConfig.SimulatedRandomLatency    = _config.GetCVar <float>("net.fakelagrand");
            netConfig.SimulatedDuplicatesChance = _config.GetCVar <float>("net.fakeduplicates");

            netConfig.ConnectionTimeout = 30000f;
#endif
            return(netConfig);
        }
Example #3
0
        public static NetServer CreateServer(NetworkOptions options)
        {
            var config = new NetPeerConfiguration(options.Identifier);

            config.AcceptIncomingConnections = true;
            config.UseMessageRecycling       = true;
            config.SetMessageTypeEnabled(NetIncomingMessageType.DiscoveryRequest, true);
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);

            config.MaximumConnections = options.ClientLimit;
            config.ConnectionTimeout  = 5;

            if (options.PingInterval > 0)
            {
                config.PingInterval = options.PingInterval / 1000f;
            }

            if (options.RetryInterval > 0)
            {
                config.ResendHandshakeInterval = config.ResendHandshakeInterval / 1000f;
            }

            if (options.Host != null && options.Host.Trim().Length > 0)
            {
                config.LocalAddress = IPAddress.Parse(options.Host);
            }

            config.Port = options.Port;

            return(new NetServer(config));
        }
Example #4
0
        /// <summary>
        /// Initialise the server, and store some test users and clients.
        /// </summary>
        private void initialise()
        {
            LogInManager.StoreNewUser("helen", "potato");
            LogInManager.StoreNewUser("test", "tomato");
            LogInManager.StoreNewUser("simon", "farshas");
            NetPeerConfiguration config = new NetPeerConfiguration(app_identifier);

            //config.BroadcastAddress = NetUtility.Resolve("* your external IP here in IPv4 format *"); // external IP of a machine that the server might be running on
            config.LocalAddress       = NetUtility.Resolve(host_name);
            config.MaximumConnections = max_connections;
            config.Port = port;
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionLatencyUpdated, true);
            config.PingInterval      = 10f;
            config.ConnectionTimeout = 100f;
            server   = new NetServer(config);
            ctSource = new CancellationTokenSource();
            server.Start();
            Globals_Server.server = server;
            Globals_Server.logEvent("Server started- host: " + config.BroadcastAddress + ", port: " + port + ", appID: " +
                                    app_identifier + ", max connections: " + max_connections);
            Client client = new Client("helen", "Char_158");

            Globals_Server.Clients.Add("helen", client);
            Client client2 = new Client("test", "Char_196");

            Globals_Server.Clients.Add("test", client2);
            Client client3 = new Client("simon", "Char_283");

            Globals_Server.Clients.Add("simon", client3);
            String        dir = Directory.GetCurrentDirectory();
            List <string> pcs = Globals_Game.pcKeys;                 // to potentially add a "create user function"

            pcs.Remove("Char_158");
            pcs.Remove("Char_195");
            pcs.Remove("Char_283");
            //dir = dir.Remove(dir.IndexOf("RepairHist_mmo"));
            String path;

            if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
            {
                path = Path.Combine(dir, "Certificates");
            }
            else
            {
                dir  = Directory.GetParent(dir).FullName;
                dir  = Directory.GetParent(dir).FullName;
                dir  = Directory.GetParent(dir).FullName;
                path = Path.Combine(dir, "Certificates");
            }
            Diplomacy.forgeAlliance("Char_283", "Char_196");
            Diplomacy.declareWar("Char_283", "Char_158");
            LogInManager.InitialiseCertificateAndRSA(path);
        }
        public static void Run()
        {
            var config = new NetPeerConfiguration("Test");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == false)
            {
                throw new LidgrenException("setting enabled message types failed");
            }

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, false);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == true)
            {
                throw new LidgrenException("setting enabled message types failed");
            }

            Console.WriteLine("Hex test: " + NetUtility.ToHexString(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }));

            if (NetBitWriter.BitsForValue(uint.MaxValue + 1ul) != 33)
            {
                throw new LidgrenException("BitCountForValue failed");
            }

            Console.WriteLine("Misc tests OK");
        }
 static void NetPeerConfigInit()
 {
     config.Port               = MediatorPort;
     config.LocalAddress       = IPAddress.Parse(MediatorIP);
     config.MaximumConnections = 10000;
     config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
 }
Example #7
0
        public AuthoryMasterServer()
        {
            LoadConfig();

            Console.WriteLine($"Creating config on port: {defaultServerPort}...");
            netPeerConfig = new NetPeerConfiguration(defaultServerAuthString);
            netPeerConfig.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            netPeerConfig.PingInterval      = 4f;
            netPeerConfig.ConnectionTimeout = 6.5f;
            netPeerConfig.Port = (int)defaultServerPort;
            Console.WriteLine("Config created.");

            Console.WriteLine("Creating NetServer...");
            NetServer = new NetServer(netPeerConfig);
            Console.WriteLine($"NetServer created on port: {defaultServerPort}.");

            DatabaseHandler = new DatabaseHandler(dbServer, dbName, dbUser, dbPassword);
            DataHandler     = DataHandler.Instance;
            MessageHandler  = OutgoingMessageHandler.Instance.Init(NetServer);

            IncomingMessageHandler = new IncomingMessageHandler(DataHandler, DatabaseHandler, NetServer);

            Console.WriteLine("Lodaing maps...");
            LoadMaps();
            Console.WriteLine("Maps loaded.");
        }
Example #8
0
        /// <summary>
        /// Initialize MapServer
        /// </summary>
        /// <param name="port">Port where the MapServer will run</param>
        /// <param name="connName">Connection string for connection</param>
        /// <param name="mapName">Name of the map</param>
        /// <param name="mapIndex">Index of the map</param>
        public void Init(int port, string connName, string mapName, int mapIndex)
        {
            MapName  = mapName;
            MapIndex = mapIndex;

            statisticsStopwatch = new Stopwatch();
            mobStopwatch        = new Stopwatch();

            statisticsStopwatch.Start();
            mobStopwatch.Start();

            statistics = Statistics.None;

            _netPeerConfig = new NetPeerConfiguration(connName);
            _netPeerConfig.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            _netPeerConfig.PingInterval      = 3f;
            _netPeerConfig.ConnectionTimeout = 6.5f;
            //_netPeerConfig.SimulatedMinimumLatency = 0.1f;
            //_netPeerConfig.SimulatedRandomLatency = 0.01f;
            _netPeerConfig.Port = (int)port;

            NetServer = new NetServer(_netPeerConfig);
            Data      = new WorldDataHandler(ServerIndex);
            OutgoingMessageHandler = new OutgoingMessageHandler(NetServer, Data);
            IncomingMessageHandler = new IncomingMessageHandler(this);

            InitTeleporter(new Vector3(450, 0, 450), 2.5f, mapIndex == 0 ? 1 : 0);

            InitSpawners(mapsFolderPath);

            Console.WriteLine("Server UP");
            ServerUp = true;
        }
Example #9
0
        public static void MainServer()
        {
            Application.EnableVisualStyles();
            ConForm = new NetworkConnector();
            // The player pressed host.
            if (SSEngine.Peer == null)
            {
                NetPeerConfiguration config = new NetPeerConfiguration("strange suits");
                config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
                SSEngine.Peer = new NetServer(config);
                SSEngine.Peer.Start();
                Debug.WriteLine("Server started; waiting 2 seconds...");
                System.Threading.Thread.Sleep(2000);

                // register with master server
                NetOutgoingMessage regMsg = SSEngine.Peer.CreateMessage();
                regMsg.Write((byte)MasterServerMessageType.RegisterHost);
                IPAddress mask;
                IPAddress adr = NetUtility.GetMyAddress(out mask);
                regMsg.Write(SSEngine.Peer.UniqueIdentifier);
                regMsg.Write(new IPEndPoint(adr, SSEngine.Peer.Port));
                Debug.WriteLine("Sending registration to master server");
                SSEngine.Peer.SendUnconnectedMessage(regMsg, SSEngine.MasterServerEndpoint);
                ConForm.tbxHost.Text = SSEngine.Peer.UniqueIdentifier.ToString();
                ConForm.StartUpdate();
            }
            else
            {
                ConForm.tbxClient.Text = SSEngine.Peer.UniqueIdentifier.ToString();
            }
            ConForm.ShowDialog();
        }
        public static void Run(NetPeer peer)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("Test");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == false)
            {
                throw new NetException("setting enabled message types failed");
            }

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, false);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == true)
            {
                throw new NetException("setting enabled message types failed");
            }

            TestContext.Out.WriteLine("Misc tests OK");

            TestContext.Out.WriteLine("Hex test: " + NetUtility.ToHexString(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }));

            if (NetUtility.BitsToHoldUInt64((ulong)UInt32.MaxValue + 1ul) != 33)
            {
                throw new NetException("BitsToHoldUInt64 failed");
            }
        }
Example #11
0
        internal ClientConnection(bool dummy)
        {
            if (!dummy)
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

                NetPeerConfiguration peerConfig = new NetPeerConfiguration("Qbes");
                peerConfig.AutoFlushSendQueue = true;
                peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.DebugMessage, true);
                peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.ErrorMessage, true);
                peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.VerboseDebugMessage, true);
                peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.WarningMessage, true);
                _Client = new NetClient(peerConfig);
                _Client.RegisterReceivedCallback(new SendOrPostCallback(ReceivedMessage));
            }
        }
Example #12
0
        /// <summary>
        /// Set up the server, bind to a socket. Use Start to fully start the server after running this
        /// </summary>
        /// <param name="configuration"></param>
        public static void InitializeServer(ServerConfiguration configuration)
        {
            Configuration = configuration;

            if (peer != null && peer.Status != NetPeerStatus.NotRunning)
            {
                Debug.LogError("cannot start server while already running");
                return;
            }

            _netPeerConfiguration      = new NetPeerConfiguration(Configuration.AppIdentifier);
            _netPeerConfiguration.Port = Configuration.ListenPort;
            _netPeerConfiguration.MaximumConnections = Configuration.MaximumConnections;
            connections = new IntDictionary <NetConnection>(Configuration.MaximumConnections);

            _netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);

            peer = new NetServer(_netPeerConfiguration);

            peer.Start();

            var serverId     = connections.Add(null);
            var serverPlayer = new Player();

            serverPlayer.Id = (ushort)serverId;
            Player.Server   = serverPlayer;

            GameState.update += Update;
        }
Example #13
0
        public void TestSetMessageTypeEnabled()
        {
            var config = new NetPeerConfiguration("Test");

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, false);
            Assert.IsFalse(config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData), "setting enabled message types failed");
        }
Example #14
0
        void InitializeClient()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("test");

            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionLatencyUpdated, true);
            config.ConnectionTimeout = 3000f;
            client = new NetClient(config);
        }
Example #15
0
        private ServerManager()
        {
            WorldHelper.SetMessagingProviders(_ClientToServer, _ServerToClient);

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            NetPeerConfiguration peerConfig = ServerWorldManager.Instance.Configuration.Network.CreateNetPeerConfigurationUdp();

            peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.DebugMessage, true);
            peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.ErrorMessage, true);
            peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.VerboseDebugMessage, true);
            peerConfig.SetMessageTypeEnabled(NetIncomingMessageType.WarningMessage, true);

            _Server = new NetServer(peerConfig);
            _Server.RegisterReceivedCallback(new SendOrPostCallback(ReceivedMessage));

            _WebServer = new WebHost(ServerWorldManager.Instance.Configuration.Network.Web);
        }
Example #16
0
        public Program()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("masterserver");

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = Game.API.MasterServer.MasterServerPort;

            peer = new NetPeer(config);
            peer.Start();
        }
Example #17
0
        static void Main(string[] args)
        {
            IPEndPoint masterServerEndpoint = NetUtility.Resolve("localhost", CommonConstants.MasterServerPort);

            NetPeerConfiguration config = new NetPeerConfiguration("game");

            config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
            config.Port = 14242;

            NetServer server = new NetServer(config);

            server.Start();

            Console.WriteLine("Server started; waiting 5 seconds...");
            System.Threading.Thread.Sleep(5000);

            var lastRegistered = -60.0f;

            while (Console.KeyAvailable == false || Console.ReadKey().Key != ConsoleKey.Escape)
            {
                // (re-)register periodically with master server
                if (NetTime.Now > lastRegistered + 60)
                {
                    // register with master server
                    NetOutgoingMessage regMsg = server.CreateMessage();
                    regMsg.Write((byte)MasterServerMessageType.RegisterHost);
                    IPAddress mask;
                    IPAddress adr = NetUtility.GetMyAddress(out mask);
                    regMsg.Write(server.UniqueIdentifier);
                    regMsg.Write(new IPEndPoint(adr, 14242));
                    Console.WriteLine("Sending registration to master server");
                    server.SendUnconnectedMessage(regMsg, masterServerEndpoint);
                    lastRegistered = (float)NetTime.Now;
                }

                NetIncomingMessage inc;
                while ((inc = server.ReadMessage()) != null)
                {
                    switch (inc.MessageType)
                    {
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        Console.WriteLine(inc.ReadString());
                        break;
                    }
                }

                System.Threading.Thread.Sleep(1);
            }

            Console.ReadKey();
        }
Example #18
0
        static void ClientServerStart()
        {
            NetPeerConfiguration config = new NetPeerConfiguration(" ");

            config.Port               = ClientPort;
            config.LocalAddress       = IPAddress.Parse(ClientIP);
            config.MaximumConnections = 10000;
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);

            MediatorServer = new NetServer(config);
            MediatorServer.Start();
        }
Example #19
0
        public override void Open(string bindip, ushort port, bool lan)
        {
            var bind = bindip == "*" ?
                       IPAddress.Any :
                       IPAddress.Parse(bindip);

            NetPeerConfiguration config = new NetPeerConfiguration(GameInfo.NAME)
            {
                Port = port,
                AcceptIncomingConnections = true
            };

            config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            config.SetMessageTypeEnabled(NetIncomingMessageType.DebugMessage, Debug.isDebugBuild);

            _server = new NetServer(config);
            _server.Start();
            var con = _server.GetConnection(new IPEndPoint(IPAddress.None, port));

            _listen = true;
        }
Example #20
0
        public PropertyBag(InfiniminerGame gameInstance)
        {
            // Initialize our network device.
            NetPeerConfiguration netConfig = new NetPeerConfiguration("InfiniminerPlus");

            netClient = new NetClient(netConfig);
            netConfig.SetMessageTypeEnabled(NetIncomingMessageType.ErrorMessage, true);
            //netClient.SimulatedMinimumLatency = 0.1f;
            //netClient.SimulatedLatencyVariance = 0.05f;
            //netClient.SimulatedLoss = 0.1f;
            //netClient.SimulatedDuplicates = 0.05f;
            netClient.Start();

            // Initialize engines.
            blockEngine     = new BlockEngine(gameInstance);
            interfaceEngine = new InterfaceEngine(gameInstance);
            playerEngine    = new PlayerEngine(gameInstance);
            skyplaneEngine  = new SkyplaneEngine(gameInstance);
            particleEngine  = new ParticleEngine(gameInstance);

            // Create a camera.
            playerCamera = new Camera(gameInstance.GraphicsDevice);
            UpdateCamera();

            // Load sounds.
            if (!gameInstance.NoSound)
            {
                soundList[InfiniminerSound.DigDirt]         = gameInstance.Content.Load <SoundEffect>("sounds/dig-dirt");
                soundList[InfiniminerSound.DigMetal]        = gameInstance.Content.Load <SoundEffect>("sounds/dig-metal");
                soundList[InfiniminerSound.Ping]            = gameInstance.Content.Load <SoundEffect>("sounds/ping");
                soundList[InfiniminerSound.ConstructionGun] = gameInstance.Content.Load <SoundEffect>("sounds/build");
                soundList[InfiniminerSound.Death]           = gameInstance.Content.Load <SoundEffect>("sounds/death");
                soundList[InfiniminerSound.CashDeposit]     = gameInstance.Content.Load <SoundEffect>("sounds/cash");
                soundList[InfiniminerSound.ClickHigh]       = gameInstance.Content.Load <SoundEffect>("sounds/click-loud");
                soundList[InfiniminerSound.ClickLow]        = gameInstance.Content.Load <SoundEffect>("sounds/click-quiet");
                soundList[InfiniminerSound.GroundHit]       = gameInstance.Content.Load <SoundEffect>("sounds/hitground");
                soundList[InfiniminerSound.Teleporter]      = gameInstance.Content.Load <SoundEffect>("sounds/teleport");
                soundList[InfiniminerSound.Jumpblock]       = gameInstance.Content.Load <SoundEffect>("sounds/jumpblock");
                soundList[InfiniminerSound.Explosion]       = gameInstance.Content.Load <SoundEffect>("sounds/explosion");
                soundList[InfiniminerSound.RadarHigh]       = gameInstance.Content.Load <SoundEffect>("sounds/radar-high");
                soundList[InfiniminerSound.RadarLow]        = gameInstance.Content.Load <SoundEffect>("sounds/radar-low");
                soundList[InfiniminerSound.RadarSwitch]     = gameInstance.Content.Load <SoundEffect>("sounds/switch");
            }

            // Create a SINGLE SPRITEBATCH FOR THE F*****G GOD DAMN STATES AND SHIT
            spriteBatch = new SpriteBatch(gameInstance.GraphicsDevice);

            //Generate a SINGLE 1px white texture
            shade = new Texture2D(gameInstance.GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            shade.SetData(new Color[] { Color.White });
        }
Example #21
0
    public void ConnectToServer()
    {
        spawnedSync.Clear();
        spawnedPlayers.Clear();

        nickname = global.player.Nickname;
        var config = new NetPeerConfiguration("Ostfront")
        {
            EnableUPnP                = true,
            ReceiveBufferSize         = 16035,
            SendBufferSize            = 16035,
            AcceptIncomingConnections = true
        };

        config.SetMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess, true);
        config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
        config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);

        _client = new NetClient(config);
        _client.Start();

        new OF_GameServer.LoopMessages(_client);

        if (!isOffline)
        {
            NetOutgoingMessage connectionMessage = _client.CreateMessage();
            //connectionMessage.Write((byte)GlobalServerTransmissionEnum.IntroduceToPublicServer);
            connectionMessage.Write(serverName);
            connectionMessage.Write(new IPEndPoint(global.GetInternal(), _client.Port));
            _client.SendUnconnectedMessage(connectionMessage, GlobalServerIP);
        }
        else
        {
            StartCoroutine("OfflineConnection");
        }

        StartCoroutine("CheckConnect");
    }
Example #22
0
        public static NetClient CreateClient(NetworkOptions options)
        {
            var config = new NetPeerConfiguration(options.Identifier == null ? "Sirius" : options.Identifier);

            config.AcceptIncomingConnections = false;
            config.UseMessageRecycling       = true;
            config.SetMessageTypeEnabled(NetIncomingMessageType.DiscoveryRequest, false);
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, false);

            config.ConnectionTimeout = 5;

            if (options.PingInterval > 0)
            {
                config.PingInterval = options.PingInterval / 1000f;
            }

            if (options.RetryInterval > 0)
            {
                config.ResendHandshakeInterval = config.ResendHandshakeInterval / 1000f;
            }

            return(new NetClient(config));
        }
Example #23
0
        /// <summary>
        /// Start local network peer.
        /// </summary>
        public Network()
        {
            m_netPeerConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            m_netPeerConfiguration.Port = APIMain.MasterServerPort;

            m_netPeer = new NetPeer(m_netPeerConfiguration);
            m_netPeer.Start();

            m_updateThread = new Thread(Update);
            m_updateThread.Start();

            m_updateServersListThread = new Thread(UpdateServerList);
            m_updateServersListThread.Start();
        }
Example #24
0
        //TODO: Refactor
        public ServerCore(ILogger loggerInstance, string appName, int port, string hailMessage)
            : base()
        {
            NetworkMessageHandler = new PacketHandler(loggerInstance);
            NetworkMessageHandler.Register <DiffieHellmanAESEncryptor>(EncryptionBase.DefaultByte);

            Port = port;
            UnhandledServerConnections = new List <ConnectionResponse>();

            //Register the default serializer
            this.NetworkMessageHandler.Register <GladNetProtobufNetSerializer>();

            ClassLogger       = loggerInstance;
            Clients           = new ConnectionCollection <ClientPeer, NetConnection>();
            ServerConnections = new ConnectionCollection <ServerPeer, NetConnection>();

            //Construction of the Lidgren server listener
            NetPeerConfiguration config = new NetPeerConfiguration(appName);

            config.Port = port;

            //Server needs a much larger than default buffer size because corruption can happen otherwise
            config.ReceiveBufferSize = 500000;
            config.SendBufferSize    = 500000;

            //This message type must be set to true so we can manage connections with hailmessages and so that we can
            //reject the majority of non-malicious malformed connection attempts
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            config.SetMessageTypeEnabled(NetIncomingMessageType.ExternalHighlevelMessage, true);

            //Reduces GC
            config.UseMessageRecycling = true;

            lidgrenServerObj = new NetServer(config);

            ExpectedClientHailMessage = hailMessage;
        }
Example #25
0
        void StartServer()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("FPSMod");

            Debug.Log("Starting Server");

            m_isServer = true;

            config.Port = ServerSettings.Port;
            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);

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

            SpawnLocalPlayer();
            Debug.Log("wID: " + m_saveWorkshopID);
            Debug.Log("p: " + ServerSettings.Private);

            if (MultiplayerLoading.UseVehiclesAndCitizens)
            {
                m_vNetworkManager = gameObject.AddComponent <VehicleNetworkManager>();
                m_cNetworkManager = gameObject.AddComponent <CitizenNetworkManager>();
            }

            if (m_saveWorkshopID != UInt64.MaxValue && !ServerSettings.Private)
            {
                try
                {
                    using (var client = new WebClient())
                    {
                        var values = new NameValueCollection
                        {
                            { "name", ServerSettings.Name.IsNullOrWhiteSpace() ? "No name" : ServerSettings.Name },
                            { "port", ServerSettings.Port.ToString() },
                            { "mapId", m_saveWorkshopID.ToString() },
                            { "modVersion", Settings.ModVersion.ToString() }
                        };
                        var    result       = client.UploadValues(Settings.ServerUrl + "/create", "POST", values);
                        string responsebody = Encoding.UTF8.GetString(result);
                        Debug.Log("Sending to masterserver: " + responsebody);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Example #26
0
        partial void ImplConnectionSetup()
        {
            _serverConfiguration = new NetPeerConfiguration(Configuration.AppIdentifier);
            _serverConfiguration.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);
            _serverConfiguration.Port = Configuration.ListenPort;
            //bit of overhead in connection count
            _serverConfiguration.MaximumConnections = (int)(Configuration.MaximumPlayers * 1.5);

#if DEBUG
            Debug.Log("Debug build. Simulated latency and packet loss/duplication is enabled.");
            _serverConfiguration.SimulatedLoss             = 0.001f;
            _serverConfiguration.SimulatedDuplicatesChance = 0.001f;
            _serverConfiguration.SimulatedMinimumLatency   = 0.1f;
            _serverConfiguration.SimulatedRandomLatency    = 0.01f;
#endif

            PlayerServer = new NetServer(_serverConfiguration);
        }
        public static void Run(NetPeer peer)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("Test");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == false)
            {
                throw new NetException("setting enabled message types failed");
            }

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, false);
            if (config.IsMessageTypeEnabled(NetIncomingMessageType.UnconnectedData) == true)
            {
                throw new NetException("setting enabled message types failed");
            }

            Console.WriteLine("Misc tests OK");

            Console.WriteLine("Hex test: " + NetUtility.ToHexString(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }));
        }
Example #28
0
    void Start()
    {
        try
        {
            Debug.Log("client try Start");
            config = new NetPeerConfiguration(" ");
            DontDestroyOnLoad(this);

            config.SetMessageTypeEnabled(NetIncomingMessageType.UnconnectedData, true);
            config.Port = 1212;

            client = new NetClient(config);

            client.Start();
            Debug.Log("client Start");
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
        }
    }
        protected internal override void Initialize()
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            //set up room server
            var roomConfig = new NetPeerConfiguration(Server.Configuration.AppIdentifier + "DPT")
            {
                AutoFlushSendQueue = true,
                Port = Server.Configuration.RoomListenPort,
                MaximumConnections = Server.Configuration.MaximumRooms
            };

            roomConfig.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);

            RoomServer = new NetServer(roomConfig);
            RoomServer.RegisterReceivedCallback(RoomCallback);
            RoomServer.Start();

            //set up player server
            var playerConfig = new NetPeerConfiguration(Server.Configuration.AppIdentifier)
            {
                AutoFlushSendQueue = true,
                Port = Server.Configuration.PlayerListenPort,
                MaximumConnections = Server.Configuration.MaximumPlayers
            };

            playerConfig.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval, true);

#if DEBUG
            Debug.Log("Debug build. Simulated latency and packet loss/duplication is enabled.");
            playerConfig.SimulatedLoss             = 0.001f;
            playerConfig.SimulatedDuplicatesChance = 0.001f;
            playerConfig.SimulatedMinimumLatency   = 0.1f;
            playerConfig.SimulatedRandomLatency    = 0.01f;
#endif

            PlayerServer = new NetServer(playerConfig);
            PlayerServer.RegisterReceivedCallback(PlayerCallback);
            PlayerServer.Start();
        }
Example #30
0
        /// <summary>
        /// Start the server
        /// </summary>
        public void StartServer()
        {
            Clients = new ClientCollection();

            // Server basic configuration
            var config = new NetPeerConfiguration(GameConfiguration.NetworkAppIdentifier)
            {
                MaximumConnections = ServerSettings.MaxConnection,
                Port = ServerSettings.Port,
                #if DEBUG
                //PingInterval = 1f, // send ping every 1 second
                //SimulatedLoss = 0.5f, // half packets lost
                //SimulatedMinimumLatency = 0.05f, // latency of 50 ms
                #endif
            };

            // To send ping to each player frequently
            config.SetMessageTypeEnabled(NetIncomingMessageType.ConnectionLatencyUpdated, true);

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

                _hostStarted = true;

                GameManager.Initialize();

                Program.Log.Info("[START]Game server has started");
                Program.Log.Info("[PORT]: " + config.Port);
            }
            catch (NetException ex)
            {
                Program.Log.Fatal(ex.Message);

                throw;
            }
        }