コード例 #1
0
ファイル: Host.cs プロジェクト: Choochoo/Ship
        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();
        }
コード例 #2
0
ファイル: CozyClient.Main.cs プロジェクト: xxy1991/cozy
 public CozyClient(string ClientName)
 {
     NetPeerConfiguration config = new NetPeerConfiguration(ClientName);
     config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
     InnerClient = new NetClient(config);
     InnerClient.RegisterReceivedCallback(RecivePacket);
 }
コード例 #3
0
ファイル: GameServer.cs プロジェクト: CloneDeath/FantasyScape
        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!");
        }
コード例 #4
0
ファイル: Connect.cs プロジェクト: CloneDeath/Xanatos
        public void Initialize()
        {
            TextBox IP = new TextBox(MainCanvas.Instance);
            IP.Text = "127.0.0.1";
            IP.SetPosition(10, 10);

            NumericUpDown Port = new NumericUpDown(MainCanvas.Instance);
            Port.Max = ushort.MaxValue;
            Port.Min = 0;
            Port.Value = 54987;
            Port.SetPosition(10, 40);

            Button Connect = new Button(MainCanvas.Instance);
            Connect.Text = "Connect";
            Connect.SetPosition(10, 70);
            Connect.Clicked += delegate(Base sender, ClickedEventArgs args) {
                NetPeerConfiguration config = new NetPeerConfiguration("Xanatos");
                Program.Connection = new NetClient(config);
                Program.Connection.Start();
                Program.Connection.Connect(IP.Text, (int)Port.Value);

                while (((NetClient)Program.Connection).ConnectionStatus != NetConnectionStatus.Connected) {
                    Thread.Sleep(500);
                    Program.Connection.ReadMessages(new List<NetIncomingMessage>());
                }
                Message.RegisterClient(Program.Connection);

                new PlayerJoining().Send();
            };
        }
コード例 #5
0
ファイル: ClientMain.cs プロジェクト: shangshen/cozy
 public Client()
 {
     NetPeerConfiguration config = new NetPeerConfiguration("CozyAnywhere");
     config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
     client                      = new NetClient(config);
     client.RegisterReceivedCallback(RecivePacket);
 }
コード例 #6
0
ファイル: NetworkMultiplayer.cs プロジェクト: JOCP9733/tank
        public NetworkMultiplayer(bool createServer = false)
            : base(GameModes.Network)
        {
            if(createServer)
                GameServer = new GameServer();

            //read network on each update
            Game.Instance.OnUpdate += ReadNetwork;

            //server config
            NetPeerConfiguration config = new NetPeerConfiguration("tank");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);

            //server creation
            Client = new NetClient(config);
            Client.Start();

            if (!createServer)
            {
                //check whether the user has a known server
                ListMenu serverMenu = new ListMenu("Do you want to connect to a given IP (if yes, enter in console)?", "tank.Code.YESORNOCHOOSENOW", ConnectionMethodSelectionCallback);
                Scene.Add(serverMenu);
            }
            else//we know that a local server must exist
                Client.DiscoverLocalPeers(14242);
            //register handler for receiving data
            OnClientData += IncomingHandler;

            //are we client, or are we dancer?
            if(!createServer)
                Console.WriteLine("client");
        }
コード例 #7
0
        static void Main()
        {
            //would block send buffer full
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            MainForm = new Form1();

            NetPeerConfiguration config = new NetPeerConfiguration("many");

            config.Port = 14242;
            config.AutoFlushSendQueue = true;
            config.SendBufferSize = 1024 * 512;
            #if DEBUG
            config.SimulatedLoss = 0.02f;
            #else
            // throw new Exception("Sample not relevant in RELEASE; statistics needed to make sense!");
            #endif
            config.MaximumConnections = 50000;

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

            var swin = new NetPeerSettingsWindow("Server settings", Program.Server);
            swin.Show();

            Application.Idle += new EventHandler(AppLoop);
            Application.Run(MainForm);
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: pr0gramm3r1/AngryTanks
		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");
		}
コード例 #9
0
ファイル: ServerMain.cs プロジェクト: shangshen/cozy
 public Server(int MaxConnections, int Port)
 {
     NetPeerConfiguration config = new NetPeerConfiguration("CozyAnywhere");
     config.MaximumConnections   = MaxConnections;
     config.Port                 = Port;
     server                      = new NetServer(config);
 }
コード例 #10
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");
 }
コード例 #11
0
 public static NetPeerConfiguration GetStandardConfiguration(this NetPeerConfiguration self)
 {
     var config = new NetPeerConfiguration("NovaRat");
     // Disable all message types
     config.DisableMessageType(NetIncomingMessageType.ConnectionApproval);
     config.DisableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated);
     config.DisableMessageType(NetIncomingMessageType.Data);
     config.DisableMessageType(NetIncomingMessageType.DebugMessage);
     config.DisableMessageType(NetIncomingMessageType.DiscoveryRequest);
     config.DisableMessageType(NetIncomingMessageType.DiscoveryResponse);
     config.DisableMessageType(NetIncomingMessageType.Error);
     config.DisableMessageType(NetIncomingMessageType.ErrorMessage);
     config.DisableMessageType(NetIncomingMessageType.NatIntroductionSuccess);
     config.DisableMessageType(NetIncomingMessageType.Receipt);
     config.DisableMessageType(NetIncomingMessageType.UnconnectedData);
     config.DisableMessageType(NetIncomingMessageType.VerboseDebugMessage);
     config.DisableMessageType(NetIncomingMessageType.WarningMessage);
     // Enable only what we need
     config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
     config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess);
     config.EnableMessageType(NetIncomingMessageType.StatusChanged);
     //config.EnableMessageType(NetIncomingMessageType.DebugMessage);
     //config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
     //config.EnableMessageType(NetIncomingMessageType.WarningMessage);
     //config.EnableMessageType(NetIncomingMessageType.ErrorMessage);
     config.AcceptIncomingConnections = true;
     // No need to assign a port, as the OS will automatically assign an available port
     return config;
 }
コード例 #12
0
        /// <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();
        }
コード例 #13
0
ファイル: Client.cs プロジェクト: uwrov/teaching
        public static void Main(string[] args)
        {
            Console.WriteLine("[CLIENT] Testing Lidgren-Network-v3...");

            NetPeerConfiguration clientConfig = new NetPeerConfiguration("test");
            clientConfig.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            NetClient client = new NetClient(clientConfig);
            client.Start();

            Console.WriteLine("IP to connect to: ");
            String ip = Console.ReadLine();
            client.Connect("192.168.1.2", 80);

            while (true)
            {
                if (client.ServerConnection != null)
                {
                    string msg = Console.ReadLine();

                    NetOutgoingMessage sendMsg = client.CreateMessage();
                    sendMsg.Write(msg);
                    client.SendMessage(sendMsg, NetDeliveryMethod.ReliableOrdered);
                }
            }
        }
コード例 #14
0
        public void StartClientConnection(string ip, string port)
        {
            _config = new NetPeerConfiguration(GameConfiguration.NetworkAppIdentifier)
            {
            #if DEBUG
                //PingInterval = 1f, // send ping every 1 second
                //SimulatedLoss = 0.5f, // from 0 to 1
                SimulatedMinimumLatency = GameConfiguration.SimulatedMinimumLatency,
            #endif
            };

            _config.EnableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated);

            _hasStarted = true;
            _connected = false;
            _disconnected = false;

            // Client initialize
            _client = new NetClient(_config);
            _client.Start();

            _messagePool = new Queue<NetIncomingMessage>();

            var threadStart = new ThreadStart(MessagePooling);
            _messagePooling = new Thread(threadStart);
            _messagePooling.Start();

            TryToConnect(ip, port);
        }
コード例 #15
0
ファイル: Client.cs プロジェクト: CyrilPaulus/2dThing
        public Client(RenderWindow window, ImageManager imageManager)
            : base(window, imageManager)
        {
            this.window = window;
            world = new RenderImage(800, 600);

            inputManager = new InputManager(this);

            ticker = new Ticker();

            window.ShowMouseCursor (false);
            window.SetFramerateLimit (60);

            NetPeerConfiguration netConfiguration = new NetPeerConfiguration("2dThing");
            client = new NetClient(netConfiguration);

            uMsgBuffer = new UserMessageBuffer();
            otherClients = new Dictionary<int, NetworkClient>();
            chat = new Chat(this);

            LoadRessources();

            blockTypeDisplay = new Cube(blockType, imageManager);
            blockTypeDisplay.Position = new Vector2f(window.Width - 2*Cube.WIDTH, window.Height - 2* Cube.HEIGHT);
            layerDisplay = new LayerDisplay(imageManager);
            layerDisplay.Position = blockTypeDisplay.Position - new Vector2f(0, 50);

            mouse = new Sprite (imageManager.GetImage("mouse"));
        }
コード例 #16
0
        /// <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;
        }
コード例 #17
0
ファイル: Client.cs プロジェクト: davidhart/micro
    public Client()
    {
        config = new NetPeerConfiguration("cars");
        config.ConnectionTimeout = 15.0f;

        client = new NetClient(config);
    }
コード例 #18
0
ファイル: WorldClientBase.cs プロジェクト: KtBkkr/Asteria
        public WorldClientBase(string protocolVersion)
        {
            this.protocolVersion = protocolVersion;

            // Net configuration
            NetPeerConfiguration cfg = new NetPeerConfiguration("Asteria");
            cfg.MaximumConnections = 1;
            cfg.ReceiveBufferSize = 4095;
            cfg.MaximumTransmissionUnit = 4095;
            #if DEBUG
            try
            {
                cfg.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            }
            catch
            {
                Logger.Output(this, "Running in debug mode but using release Lidgren library version, Lidgren debug messages disabled!");
            }
            #endif
            client = new NetClient(cfg);
            client.Start();

            // Create objects needed.
            sendingQ = new Queue<ClientToServerMessage>(64);
            receivingQ = new Queue<NetIncomingMessage>(128);
            newDataArrivedEvent = new AutoResetEvent(false);

            messages = new Dictionary<MessageType, List<ServerToClientMessage>>();
            serializer = new ClientToServerMessageSerializer();
            deserializer = new ServerToClientMessageSerializer();

            isRunning = true;
        }
コード例 #19
0
ファイル: FrmServer.cs プロジェクト: Rosthouse/Multi-Pac
        public void InitializeServer()
        {
            gameStateManager = new GameStateManager();

            //string ip = "147.87.243.27";
            serverConfig = new NetPeerConfiguration("pacman");
            //serverConfig.LocalAddress = IPAddress.Parse(ip);
            serverConfig.Port = 666;

            try
            {
                server = new NetServer(serverConfig);
                server.Start();
                networkManager = new ServerNetworkManager(server);
                WriteToLog("Server wurde gestartet...");
            }
            catch (Exception)
            {
                WriteToLog("Fehler! Server nicht gestartet...");
            }

            //networkManager = new NetworkManager(server);
            gameTime = new ServerGameTime();

            inputQueue = new SortedSet<Command>(new MovementComparer());
        }
コード例 #20
0
ファイル: Server.cs プロジェクト: Insality/essence-of-shadows
        /// <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();
        }
コード例 #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NetworkImp"/> class.
        /// </summary>
        public NetworkImp()
        {
            _netConfig = new NetPeerConfiguration("FUSEE3D");

            IncomingMsg = new List<INetworkMsg>();

            _config = new NetConfigValues
                          {
                              SysType = SysType.None,
                              DefaultPort = 14242,
                              Discovery = false,
                              ConnectOnDiscovery = false,
                              DiscoveryTimeout = 5000,
                              RedirectPackets = false,
                          };

            // _netConfig.RedirectedPacketsList.CollectionChanged += PackageCapture;
            Connections = new List<INetworkConnection>();

            Status = new NetStatusValues
            {
                Connected = false,
                LastStatus = ConnectionStatus.None
            };
        }
コード例 #22
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);
 }
コード例 #23
0
ファイル: SpaceClient.cs プロジェクト: FingerInSky/SpaceCrush
        public SpaceClient()
        {
            config = Constants.GetConfig();
            client = new NetClient(config);

            ClientStarted = false;
        }
コード例 #24
0
ファイル: Client.cs プロジェクト: uwrov/teaching
        public static void Main(string[] args)
        {
            Console.WriteLine("[CLIENT] Testing Lidgren-Network-v3...");

            NetPeerConfiguration clientConfig = new NetPeerConfiguration("test");
            clientConfig.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            NetClient client = new NetClient(clientConfig);
            client.Start();

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            client.RegisterReceivedCallback(new SendOrPostCallback(GotMessage));

            Console.WriteLine("IP to connect to: ");
            String ip = Console.ReadLine();

            client.Connect(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), 12345));

            while(true) {
                string msg = Console.ReadLine();

                NetOutgoingMessage sendMsg = client.CreateMessage();
                sendMsg.Write("[CLIENT] " + msg);
                client.SendMessage(sendMsg, NetDeliveryMethod.ReliableOrdered);
            }
        }
コード例 #25
0
 public Client_Model2()
 {
     _netconfig = new NetPeerConfiguration("SkyNet");
     _client = new NetClient(_netconfig);
     _assembly = new SuperAssembly("Client");
     _listen=new Thread(Listen);
 }
コード例 #26
0
ファイル: NetworkClient.cs プロジェクト: fusspawn/sobriety
 public NetworkClient(string Host, int Port)
 {
     Config = new NetPeerConfiguration("GameServer01");
     ClientConnection = new NetClient(Config);
     ClientConnection.Start();
     ClientConnection.Connect(Host, Port);
 }
コード例 #27
0
 public Server_Model2()
 {
     _netconfig = new NetPeerConfiguration("SkyNet") { Port = 9000 };
     _server = new NetServer(_netconfig);
     _assembly = new SuperAssembly("Server");
     _thread = new Thread(Thread);
 }
コード例 #28
0
ファイル: Network.cs プロジェクト: JamieH/AudioGap
        public static void Connect(IPEndPoint endpoint, MMDevice device, ICodec codec)
        {
            var config = new NetPeerConfiguration("airgap");

            _client = new NetClient(config);
            _client.RegisterReceivedCallback(MessageReceived);

            _client.Start();

            _waveIn = new WasapiLoopbackCapture(device);
            _codec = codec;

            _sourceFormat = _waveIn.WaveFormat;
            _targetFormat = new WaveFormat(_codec.SampleRate, _codec.Channels); // format to convert to

            _waveIn.DataAvailable += SendData;
            _waveIn.RecordingStopped += (sender, args) => Console.WriteLine("Stopped");
            // TODO: RecordingStopped is called when you change the audio device settings, should recover from that

            NetOutgoingMessage formatMsg = _client.CreateMessage();
            formatMsg.Write(_targetFormat.Channels);
            formatMsg.Write(_targetFormat.SampleRate);
            formatMsg.Write(codec.Name);

            _client.Connect(endpoint, formatMsg);
        }
コード例 #29
0
ファイル: WizardryGameServer.cs プロジェクト: nezek6/Wizardry
        /// <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();
        }
コード例 #30
0
 // Only for Introducer's NetworkServer
 public static NetPeerConfiguration GetStandardConfiguration(this NetPeerConfiguration self, int listeningPort)
 {
     var config = new NetPeerConfiguration("NovaRat");
     // Disable all message types
     config.DisableMessageType(NetIncomingMessageType.ConnectionApproval);
     config.DisableMessageType(NetIncomingMessageType.ConnectionLatencyUpdated);
     config.DisableMessageType(NetIncomingMessageType.Data);
     config.DisableMessageType(NetIncomingMessageType.DebugMessage);
     config.DisableMessageType(NetIncomingMessageType.DiscoveryRequest);
     config.DisableMessageType(NetIncomingMessageType.DiscoveryResponse);
     config.DisableMessageType(NetIncomingMessageType.Error);
     config.DisableMessageType(NetIncomingMessageType.ErrorMessage);
     config.DisableMessageType(NetIncomingMessageType.NatIntroductionSuccess);
     config.DisableMessageType(NetIncomingMessageType.Receipt);
     config.DisableMessageType(NetIncomingMessageType.UnconnectedData);
     config.DisableMessageType(NetIncomingMessageType.VerboseDebugMessage);
     config.DisableMessageType(NetIncomingMessageType.WarningMessage);
     // Enable only what we need
     config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
     config.EnableMessageType(NetIncomingMessageType.NatIntroductionSuccess);
     config.EnableMessageType(NetIncomingMessageType.StatusChanged);
     //config.EnableMessageType(NetIncomingMessageType.DebugMessage);
     //config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
     //config.EnableMessageType(NetIncomingMessageType.WarningMessage);
     //config.EnableMessageType(NetIncomingMessageType.ErrorMessage);
     config.Port = listeningPort;
     config.AcceptIncomingConnections = true;
     return config;
 }
コード例 #31
0
        internal NetConnection(NetPeer peer, NetEndPoint remoteEndPoint)
        {
            m_peer = peer;
            m_peerConfiguration    = m_peer.Configuration;
            m_status               = NetConnectionStatus.None;
            m_outputtedStatus      = NetConnectionStatus.None;
            m_visibleStatus        = NetConnectionStatus.None;
            m_remoteEndPoint       = remoteEndPoint;
            m_sendChannels         = new NetSenderChannelBase[NetConstants.NumTotalChannels];
            m_receiveChannels      = new NetReceiverChannelBase[NetConstants.NumTotalChannels];
            m_queuedOutgoingAcks   = new NetQueue <NetTuple <NetMessageType, int> >(4);
            m_queuedIncomingAcks   = new NetQueue <NetTuple <NetMessageType, int> >(4);
            m_statistics           = new NetConnectionStatistics(this);
            m_averageRoundtripTime = -1.0f;
            m_currentMTU           = m_peerConfiguration.MaximumTransmissionUnit;

            //Set the remote identifier
            m_remoteUniqueIdentifier = Interlocked.Increment(ref remoteUniqueIdCount);
        }
コード例 #32
0
 /// <summary>
 /// NetPeer constructor
 /// </summary>
 public NetPeer(NetPeerConfiguration config)
 {
     m_configuration             = config;
     m_statistics                = new NetPeerStatistics(this);
     m_releasedIncomingMessages  = new NetQueue <NetIncomingMessage>(4);
     m_unsentUnconnectedMessages = new NetQueue <NetTuple <NetEndPoint, NetOutgoingMessage> >(2);
     m_connections               = new List <NetConnection>();
     m_connectionLookup          = new Dictionary <NetEndPoint, NetConnection>();
     m_handshakes                = new Dictionary <NetEndPoint, NetConnection>();
     if (m_configuration.LocalAddress.AddressFamily == AddressFamily.InterNetworkV6)
     {
         m_senderRemote = (EndPoint) new IPEndPoint(IPAddress.IPv6Any, 0);
     }
     else
     {
         m_senderRemote = (EndPoint) new IPEndPoint(IPAddress.Any, 0);
     }
     m_status = NetPeerStatus.NotRunning;
     m_receivedFragmentGroups = new Dictionary <NetConnection, Dictionary <int, ReceivedFragmentGroup> >();
 }
コード例 #33
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);
                }
            }
        }
コード例 #34
0
 /// <summary>
 /// Constructs the server with a given configuration.
 /// </summary>
 public NetServer(NetPeerConfiguration config) : base(config)
 {
     config.AcceptIncomingConnections = true;
 }
コード例 #35
0
		/// <summary>
		/// NetClient constructor
		/// </summary>
		/// <param name="config"></param>
		public NetClient(NetPeerConfiguration config)
			: base(config)
		{
			config.AcceptIncomingConnections = false;
		}