Example #1
0
        public ServerDiscovery(string appId, int port, ServerUpdatedCallbackDelegate serverUpdatedAction)
        {
            if (serverUpdatedAction == null)
            {
                throw new ArgumentNullException(nameof(serverUpdatedAction));
            }

            this.port = port;
            this.serverUpdatedAction = serverUpdatedAction;

            foundServers    = new Dictionary <IPEndPoint, Server>();
            publicEndPoints = new Dictionary <string, IPEndPoint>();
            jsonParser      = new JsonParser();

            NetPeerConfiguration config = new NetPeerConfiguration(appId);

            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
#if NETWORK_DEBUG
            config.EnableMessageType(NetIncomingMessageType.DebugMessage);
            config.EnableMessageType(NetIncomingMessageType.ErrorMessage);
            config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            config.EnableMessageType(NetIncomingMessageType.WarningMessage);
#else
            config.DisableMessageType(NetIncomingMessageType.DebugMessage);
            config.DisableMessageType(NetIncomingMessageType.ErrorMessage);
            config.DisableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            config.DisableMessageType(NetIncomingMessageType.WarningMessage);
#endif
            client = new NetClient(config);
            client.Start();

            waitEvent = new AutoResetEvent(false);

            threadUpdate = new Thread(OnHandleMessagesThread);
            threadUpdate.IsBackground = true;
            threadUpdate.Start();

            threadDiscovery = new Thread(OnPeriodicDiscoveryThread);
            threadDiscovery.IsBackground = true;
            threadDiscovery.Priority     = ThreadPriority.Lowest;
            threadDiscovery.Start();
        }
Example #2
0
        public MineWorldServer()
        {
            NetPeerConfiguration netConfig = new NetPeerConfiguration("MineWorld");

            netConfig.Port = Constants.MineworldPort;
            netConfig.MaximumConnections = 2;
            netConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            netConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            netConfig.DisableMessageType(NetIncomingMessageType.UnconnectedData);
            Server         = new NetServer(netConfig);
            GameWorld      = new GameWorld(this);
            Console        = new MineWorldConsole(this);
            ServerListener = new ServerListener(Server, this);
            ServerSender   = new ServerSender(Server, this);
            Listener       = new Thread(ServerListener.Start);
            MapManager     = new MapManager();
            PlayerManager  = new PlayerManager();
            Configloader   = new ConfigFile("Data/Settings.ini");
        }
Example #3
0
    private void Start()
    {
        NetPeerConfiguration config = new NetPeerConfiguration("MMO");

        //config.EnableUPnP = true;
        BESClient = new NetClient(config);
        //BESClient.UPnP.ForwardPort(8002, "Forwarded the main server's port to connect to");
        BESClient.Start();
        NetOutgoingMessage message = BESClient.CreateMessage();

        message.Write((byte)2);         //CONNECT
#if UNITY_EDITOR
        serverIp = File.ReadAllText("../ip.txt");
        BESClient.Connect(serverIp, 8002, message);
#else
        BESClient.Connect(serverIp, 8002, message);
#endif
        InvokeRepeating("PingBES", 5, 5);
    }
        public override void Initialize(Core gameCore)
        {
            Config.Changed += Config_Changed;
            ConfigData      = Config.GetSectionAs <NetworkingConfig>("serverNetworking");

            var netConfig = new NetPeerConfiguration(ConfigData.Identifier)
            {
                LocalAddress = IPAddress.Parse(ConfigData.BindAddress),
                Port         = ConfigData.BindPort
            };

            netConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

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

            logger.Debug("Started networking, listening on {0}:{1}.", ConfigData.BindAddress, ConfigData.BindPort);
            logger.Debug("Network identifier {0}.", ConfigData.Identifier);
        }
Example #5
0
        protected NetPeerBase(NetPeerConfiguration config)
        {
            this.Config       = config;
            this.baseHandlers = new Dictionary <NetIncomingMessageType, Action <NetIncomingMessage> >();
            handlers          = new Action <byte, NetIncomingMessage> [byte.MaxValue + 1];

            // Add some default handlers
            SetBaseHandler(NetIncomingMessageType.Data, (msg) =>
            {
                byte id     = msg.PeekByte(); // Peek ID bye.
                var handler = handlers[id];   // Find handler. May be null.
                if (handler == null)
                {
                    Warn($"Received data message of ID {id}, but not handler exists to process it!");
                }
                else
                {
                    msg.ReadByte(); // Consume the ID byte.
                    handler.Invoke(id, msg);
                }
            });
            SetBaseHandler(NetIncomingMessageType.DebugMessage, (msg) =>
            {
                Log(msg.ReadString());
            });
            SetBaseHandler(NetIncomingMessageType.WarningMessage, (msg) =>
            {
                Warn(msg.ReadString());
            });
            SetBaseHandler(NetIncomingMessageType.ErrorMessage, (msg) =>
            {
                Error(msg.ReadString());
            });
            SetBaseHandler(NetIncomingMessageType.StatusChanged, (msg) =>
            {
                var status = (NetConnectionStatus)msg.ReadByte();
                if (LogStatusChange)
                {
                    Trace($"Status: {msg.SenderEndPoint}, {status}");
                }
                OnStatusChange?.Invoke(msg.SenderConnection, status, msg);
            });
        }
Example #6
0
        public override void Init()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            UIMan          = new UIManager();
            UIMan.KeyDown += new KeyPressEventHandler(UIMan_KeyDown);

            text       = new Text(new Vector2(50, GraphicsDevice.PresentationParameters.BackBufferHeight - 50), "find and select a host");
            text.Color = Color.Red;
            UIMan.AddControl(text);

            SolidButton hostsBut = new SolidButton(Vector2.One * 50, 200, 75);

            hostsBut.Text           = "find hosts";
            hostsBut.MouseLeftDown += new MouseClickEventHandler(hostsBut_MouseLeftDown);

            UIMan.AddControl(hostsBut);
            hlistStart = hostsBut.Position + Vector2.UnitY * (hostsBut.Height + 100);

            SolidButton jHuman = new SolidButton(new Vector2(500, 50), 200, 100);

            jHuman.Text           = "reg as Human";
            jHuman.MouseLeftDown += new MouseClickEventHandler(jHuman_MouseLeftDown);
            UIMan.AddControl(jHuman);

            SolidButton jWumpus = new SolidButton(new Vector2(750, 50), 200, 100);

            jWumpus.Text           = "reg as Wumpus";
            jWumpus.MouseLeftDown += new MouseClickEventHandler(jWumpus_MouseLeftDown);
            UIMan.AddControl(jWumpus);

            SolidButton fBut = new SolidButton(new Vector2(750, 250), 200, 100);

            fBut.Text           = "start!";
            fBut.MouseLeftDown += new MouseClickEventHandler(fBut_MouseLeftDown);
            UIMan.AddControl(fBut);

            NetPeerConfiguration config = new NetPeerConfiguration("omron");

            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            client = new NetClient(config);
            client.Start();
        }
Example #7
0
    void Awake()
    {
        NetPeerConfiguration config = new NetPeerConfiguration("uaimh");

        config.SimulatedMinimumLatency = 0.1f;
        if (isHost)
        {
            config.Port = 3074;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            server = new NetServer(config);
            server.Start();
        }
        else
        {
            client = new NetClient(config);
            client.Start();
            client.Connect("127.0.0.1", 3074);
        }
    }
Example #8
0
        /// <inheritdoc />
        public void StartServer(NetPeerConfiguration netConfig)
        {
            if (ManagedApplicationBase != null)
            {
                throw new InvalidOperationException("Server is already started.");
            }

            ManagedApplicationBase = new InternalUnityApplicationBase(new TDeserializationStrategy(), new TSerializationStrategy(), Logger, this);

            //start the server
            ManagedApplicationBase.StartServer(netConfig);

            ISerializerRegistry serializerRegistry = new TSerializerRegistry();

            //First call the managed appbase's register
            ManagedApplicationBase.RegisterTypes(serializerRegistry);

            RegisterTypes(serializerRegistry);
        }
Example #9
0
        internal void ConnectToService(IPEndPoint remotePoint)
        {
            ThrowIfDisposed();

            if (Interlocked.CompareExchange(ref state, (int)PeerState.ConnectedToService, (int)PeerState.NotConnected) != (int)PeerState.NotConnected)
            {
                throw new InvalidOperationException("Peer has not right state.");
            }

            if (handler != null && handler.Status == NetPeerStatus.Running)
            {
                throw new ArgumentException("Already runned.");
            }

            var config = new NetPeerConfiguration(NetConfigString);

            config.Port = 0;
            config.AcceptIncomingConnections = true;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            if (remotePoint.AddressFamily == AddressFamily.InterNetworkV6)
            {
                config.LocalAddress = IPAddress.IPv6Any;
            }

            handler = new NetPeer(config);
            syncContext.Send(RegisterReceived, handler);
            handler.Start();

            var hail = handler.CreateMessage();

            using (var client = ClientModel.Get())
            {
                var localPoint = new IPEndPoint(Connection.GetIpAddress(remotePoint.AddressFamily), handler.Port);

                hail.Write(client.User.Nick);
                hail.Write(localPoint);
            }

            serviceConnection = handler.Connect(remotePoint, hail);

            ClientModel.Logger.WriteDebug("AsyncPeer.ConnectToService({0})", remotePoint);
        }
Example #10
0
File: Program.cs Project: JueZ/ITP
        public static void ConnectToServer()
        {
            NetPeerConfiguration netconfig = new NetPeerConfiguration("game");

            netclient = new NetClient(netconfig);

            if (SynchronizationContext.Current == null)
            {
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            }


            netclient.RegisterReceivedCallback(new SendOrPostCallback(ReceivedData));
            netclient.Start();

            NetOutgoingMessage message = netclient.CreateMessage("Connect");

            netclient.Connect(settings.ServerAdresse, settings.GamePort, message);
        }
        public MainWindow()
        {
            InitializeComponent();

            txtUserName.Text        = "User" + new Random().Next(10000);
            cbChatRooms.ItemsSource = _rooms;

            var builder = new ContainerBuilder();

            //register core messages
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(EmptyMessage)))
            .Where(x => x.IsAssignableTo <Message>() && x != typeof(Message))
            .As <Message>();

            //register domain messages
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(IChatLogin)))
            .Where(x => x.IsAssignableTo <Message>() && x != typeof(Message))
            .As <Message>();

            //register domain service definitions and proxies
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(IChatLogin)))
            .Where(x => x.IsAssignableTo <NetProxy>() && x != typeof(NetProxy))
            .As <NetProxy>();

            builder.RegisterType <OperationDispatcher>().As <IOperationDispatcher>().SingleInstance();
            builder.RegisterType <MessageFactory>().As <IMessageFactory>().SingleInstance();
            //builder.Register(c => new PhotonNetClient("MouseChat")).As<INetProvider>().SingleInstance();
            var netConf = new NetPeerConfiguration("ChatApp")
            {
                ConnectionTimeout = 10000,
            };

            builder.Register(x => new LidgrenNetProvider(netConf)).As <INetProvider>().SingleInstance();
            builder.RegisterType <ClientNode>().As <IClientNode>();
            var container = builder.Build();

            _node = container.Resolve <IClientNode>();
            //start node thread and init network
            _node.Start();

            btnJoin.IsEnabled = false;
            Closing          += (sender, e) => _node.Stop();
        }
Example #12
0
        public static void Start(MasterServerForm form)
        {
            RunServer = true;
            Form      = form;

            var config = new NetPeerConfiguration("masterserver");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.Port = Port;

            var peer = new NetPeer(config);

            peer.Start();

            Form.WriteLine("Master server started!");
            Task.Run(() => RemoveExpiredServers());

            CheckMasterServerListed();

            while (RunServer)
            {
                NetIncomingMessage msg;
                while ((msg = peer.ReadMessage()) != null)
                {
                    switch (msg.MessageType)
                    {
                    case NetIncomingMessageType.DebugMessage:
                    case NetIncomingMessageType.VerboseDebugMessage:
                    case NetIncomingMessageType.WarningMessage:
                    case NetIncomingMessageType.ErrorMessage:
                        Form.WriteLine("ERROR! :" + msg.ReadString());
                        break;

                    case NetIncomingMessageType.UnconnectedData:
                        var messageBytes = msg.ReadBytes(msg.LengthBytes);
                        var message      = MasterServerMessageFactory.Deserialize(messageBytes, DateTime.UtcNow.Ticks) as IMasterServerMessageBase;
                        HandleMessage(message, msg, peer);
                        break;
                    }
                }
            }
            peer.Shutdown("shutting down");
        }
Example #13
0
        public void Connect(string ipstring)
        {
            var config = new NetPeerConfiguration("Asteroid")
            {
                Port = Convert.ToInt32("14242"),
                SimulatedMinimumLatency = 0.1f,
                //SimulatedLoss = 0.1f
            };

            config.EnableMessageType(NetIncomingMessageType.WarningMessage);
            config.EnableMessageType(NetIncomingMessageType.VerboseDebugMessage);
            config.EnableMessageType(NetIncomingMessageType.ErrorMessage);
            config.EnableMessageType(NetIncomingMessageType.Error);
            config.EnableMessageType(NetIncomingMessageType.DebugMessage);
            //config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            config.EnableMessageType(NetIncomingMessageType.Data);
            netServer = new NetServer(config);
            netServer.Start();
        }
Example #14
0
        public static void Initialize(MobileFortressClient game)
        {
            Game = game;
            NetPeerConfiguration config = new NetPeerConfiguration("Mobile Fortress");

            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.EnableMessageType(NetIncomingMessageType.WarningMessage);
            config.EnableMessageType(NetIncomingMessageType.DebugMessage);
            //config.EnableUPnP = true;
            config.Port = Port;
            config.SimulatedMinimumLatency = 0.0025f;
            config.SimulatedRandomLatency  = 0.002f;
            config.SimulatedLoss           = 0.0001f;

            Client = new NetClient(config);
            Client.Start();
            NetworkAddress = "127.0.0.1";
        }
Example #15
0
        internal static void Initialize()
        {
            // Clean out the player list
            Online.players.Clear();

            // Start Client and attempt connection to the MoboServer
            Config = new NetPeerConfiguration("Mobo");
            Client = new NetClient(Network.Config);
            Client.Start();
            Client.Connect(SettingsManager.getServerIP(), SettingsManager.getPort());
            Console.WriteLine(Client.UniqueIdentifier);

            System.Threading.Thread.Sleep(300);

            // Send a connection request
            out_message = Client.CreateMessage();
            out_message.Write(CONNECT);
            out_message.Write(Client.UniqueIdentifier);
            out_message.Write(SettingsManager.getUsername());
            out_message.Write(0);
            out_message.Write(0);
            Client.SendMessage(out_message, NetDeliveryMethod.ReliableOrdered);

            // Wait a little to ensure message sent
            System.Threading.Thread.Sleep(300);

            // Use client status to work out whether we are connected or not
            string status = Client.ConnectionStatus.ToString();

            if (status.Equals("None"))
            {
                status    = "Server ONLINE";
                connected = true;
            }
            if (status.Equals("Disconnected"))
            {
                status    = "Server OFFLINE";
                connected = false;
            }

            ScreenManager.messageList.Add(Client.Status.ToString(), MessageType.Network);
            ScreenManager.messageList.Add(status, MessageType.Network);
        }
Example #16
0
        public void Awake()
        {
            instance = this;
            DontDestroyOnLoad(this);
            GetUserInfo.UpdateUserInfo();
            playerInfo = new PlayerInfo(GetUserInfo.GetUserName(), GetUserInfo.GetUserID());
            NetPeerConfiguration Config = new NetPeerConfiguration("BeatSaberMultiplayer")
            {
                MaximumHandshakeAttempts = 2, AutoFlushSendQueue = false
            };

            networkClient = new NetClient(Config);

#if DEBUG
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            WritePackets();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
#endif
        }
Example #17
0
        /// <summary>
        /// The connect.
        /// </summary>
        public void Connect(string serverName, string IP)
        {
            var config = new NetPeerConfiguration(serverName)
            {
                Port = Convert.ToInt32("14242"),
                // SimulatedMinimumLatency = 0.2f,
                // SimulatedLoss = 0.1f
            };

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

            this.netServer = new NetServer(config);
            this.netServer.Start();
        }
Example #18
0
        public override void initializeConnection()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("StardewValley");

            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            config.Port = 24642;
            config.ConnectionTimeout  = 120f;
            config.PingInterval       = 5f;
            config.MaximumConnections = 4;
            config.EnableUPnP         = true;
            this.server = new NetServer(config);
            this.server.Start();
            this.server.UPnP.ForwardPort(24642, "Stardew Valley Server");
            this.mapServerThread = new Thread(new ThreadStart(AsynchronousSocketListener.StartListening));
            this.mapServerThread.Start();
            Game1.player.uniqueMultiplayerID = this.server.UniqueIdentifier;
            Game1.serverHost = Game1.player;
        }
Example #19
0
        private void OnConnectButtonClick(object sender, EventArgs e)
        {
            string ipPort = textBox3.Text;

            if (textBox2.Text.Count() == 0)
            {
                Write("CLIENT", "You require a username to connect.");
                return;
            }
            if (ipPort.Contains(':'))
            {
                string ip   = ipPort.Substring(0, ipPort.IndexOf(":"));
                string port = ipPort.Substring(ipPort.IndexOf(":") + 1);
                int    portNum;
                if (Int32.TryParse(port, out portNum))
                {
                    try {
                        NetPeerConfiguration npConfig = new NetPeerConfiguration("MyExampleName");
                        client = new NetClient(npConfig);
                        client.Start();
                        NetOutgoingMessage usernameApproval = client.CreateMessage();
                        usernameApproval.Write(textBox2.Text);
                        client.Connect(ip, portNum, usernameApproval);
                        client.RegisterReceivedCallback(new SendOrPostCallback(OnIncomingMessage));
                        textBox1.Enabled = true;
                        textBox2.Enabled = false;
                        textBox3.Enabled = false;
                        button1.Enabled  = false;
                    } catch {
                        Write("CLIENT", "You messed up IP/port somehow.");
                    }
                }
                else
                {
                    Write("CLIENT", "Your port must be an integer!");
                }
            }
            else
            {
                Write("CLIENT", "Your IP/port string must be separated by a colon!");
            }
        }
Example #20
0
        private void SetupSocket(BadNetworkSimulation badNetworkSimulation)
        {
            // Try each known port to see if we can open a socket...
            for (int i = 0; i < appConfig.KnownPorts.Length; i++)
            {
                try
                {
                    NetPeerConfiguration config = CreateNetPeerConfiguration(badNetworkSimulation);
                    config.Port = appConfig.KnownPorts[i];
                    netPeer     = new NetPeer(config);
                    netPeer.Start();

                    Log("Socket opened on port " + PortNumber);
                    return;
                }
                catch (SocketException socketException) // Probably port unavailable
                {
                    if (socketException.SocketErrorCode != SocketError.AddressAlreadyInUse)
                    {
                        throw; // Actually, it was something else
                    }
                    else
                    {
                        continue; // Try the next port
                    }
                }
            }


            Log("Known port unavailable, auto-assigning port...");
            {
                // Try again with auto-assigned port
                NetPeerConfiguration config = CreateNetPeerConfiguration(badNetworkSimulation);
                config.DisableMessageType(NetIncomingMessageType.DiscoveryRequest); // <- will enable when we need it

                config.Port = 0;
                netPeer     = new NetPeer(config);
                netPeer.Start();

                Log("Socket opened on port " + PortNumber);
            }
        }
Example #21
0
        /// <summary>Inits networkssystems configures settings for lidgrens networks framework.</summary>
        public override void Init()
        {
            _timestart = DateTime.Now;
            _config    = new NetPeerConfiguration("Sap6_Networking")
            {
                Port = _localport,
                AcceptIncomingConnections = true,
                UseMessageRecycling       = true
            };
            _config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            _config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            _config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            //_config.SimulatedLoss = 0.05f;

            _peer = new NetPeer(_config);
            _peer.Start();
            _peer.DiscoverLocalPeers(_searchport);

            Game1.Inst.Scene.OnEvent("send_to_peer", data => this.SendObject((string)data, "metadata"));
            Game1.Inst.Scene.OnEvent("search_for_peers", data => _peer.DiscoverLocalPeers(_searchport));
            Game1.Inst.Scene.OnEvent("send_start_game",
                                     data =>
            {
                this.SendObject(data, "StartEvent");
                _isMaster     = true;
                _scanForPeers = false;
            });
            Game1.Inst.Scene.OnEvent("send_menuitem", data =>
            {
                var datasend = (MenuItem)data;
                this.SendObject(datasend.CText, datasend.Id);
            });



            DebugOverlay.Inst.DbgStr((a, b) => $"Cons: {_peer.Connections.Count} IsMaster: {_isMaster}");
            DebugOverlay.Inst.DbgStr((a, b) => $"Re: {kbps} kb/s");

            players.Add(new NetworkPlayer {
                IP = _peer.Configuration.BroadcastAddress.ToString(), Time = _timestart, You = true
            });
        }
Example #22
0
        /// <summary>
        /// Initializes the network according to the provided role
        /// </summary>
        /// <param name="role">The role to use</param>
        public void Start(NetworkRole role)
        {
            Role = role;

            var config = new NetPeerConfiguration(Configuration.ApplicationName);

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

#if DEBUG
            // Note: these only exist on Lidgren in DEBUG mode
            // Allows simulation of slow/problematic networks
            config.SimulatedLoss             = Configuration.SimulatedLoss;
            config.SimulatedMinimumLatency   = Configuration.SimulatedMinimumLatencySeconds;
            config.SimulatedRandomLatency    = Configuration.SimulatedRandomLatencySeconds;
            config.SimulatedDuplicatesChance = Configuration.SimulatedDuplicateChance;
#endif

            entities = new List <INetworkEntity>();


            switch (Role)
            {
            case NetworkRole.Client:
                network = new NetClient(config);
                log.Info("Starting client.");
                break;

            case NetworkRole.Server:
                // server is always client 1
                ClientId    = 1;
                config.Port = Configuration.ApplicationPort;
                network     = new NetServer(config);
                log.Info("Starting server on port:" + Configuration.ApplicationPort);
                break;
            }
            network.Start();
        }
Example #23
0
        public void Start(World world, Camera camera, string ip, int port, string nickname)
        {
            Connected   = false;
            this.world  = world;
            this.camera = camera;
            world.SetNetwork(this);
            if (ip.Length <= 0)
            {
                ip = "127.0.0.1";
            }
            if (port == 0)
            {
                port = Universal.DEFAULT_PORT;
            }
            if (nickname.Length <= 0)
            {
                nickname = "Player" + (random.Next() % 9999);
            }
            NetPeerConfiguration config = new NetPeerConfiguration(Universal.ID);

            client = new NetClient(config);
            NetOutgoingMessage outmsg = client.CreateMessage();

            client.Start();
            outmsg.Write((byte)Packets.Connect);
            outmsg.Write(Universal.GAME_VERSION);
            outmsg.Write(nickname);
            client.Connect(ip, port, outmsg);
            Console.WriteLine("Connecting...");
            Connect();
            if (Connected)
            {
                Console.WriteLine("Connected!");
                updateTimer          = new Timer(50);
                updateTimer.Elapsed += new ElapsedEventHandler(UpdateElapsed);
                updateTimer.Start();
            }
            else
            {
                Console.WriteLine("Connect failed.");
            }
        }
Example #24
0
        private AccountService()
        {
            _config      = new NetPeerConfiguration("AccountService");
            _config.Port = 9595;
            _listener    = new NetServer(_config);
            _invoker     = new LoginCmdInvoker();
            _listener.Start();
            _peerListenTask = new Task(() => _invoker.PeerListener(_listener));
            _peerListenTask.Start();
            Thread.Sleep(50);


            logger.Info("#####Net Peer Configurations#####");
            logger.Info("Application Identifier: {0}", _config.AppIdentifier);
            logger.Info("Local Address: {0}", _config.LocalAddress);
            logger.Info("Port: {0}", _config.Port);
            logger.Info("Broadcast Address: {0}", _config.BroadcastAddress);
            logger.Info("Network ThreadName: {0}", _config.NetworkThreadName);
            logger.Info("Auto Expand MTU: {0}", _config.AutoExpandMTU);
            logger.Info("Auto Flush Send Queue: {0}", _config.AutoFlushSendQueue);
            logger.Info("Accept Incoming Connections: {0}", _config.AcceptIncomingConnections);
            logger.Info("Connection Timeout: {0}", _config.ConnectionTimeout);
            logger.Info("Default Outgoing Message Capacity: {0}", _config.DefaultOutgoingMessageCapacity);
            logger.Info("Enable UPnP: {0}", _config.EnableUPnP);
            logger.Info("Expand MTU Fail Attempts: {0}", _config.ExpandMTUFailAttempts);
            logger.Info("Expand MTU Frequency: {0}", _config.ExpandMTUFrequency);
            logger.Info("Maximum Connections: {0}", _config.MaximumConnections);
            logger.Info("Maximum Handshake Attempts: {0}", _config.MaximumHandshakeAttempts);
            logger.Info("Maximum Transmission Unit: {0}", _config.MaximumTransmissionUnit);
            logger.Info("Ping Interval: {0}", _config.PingInterval);
            logger.Info("Receive Buffer Size: {0}", _config.ReceiveBufferSize);
            logger.Info("Send Buffer Size: {0}", _config.SendBufferSize);
            logger.Info("Resend Handshake Interval: {0}", _config.ResendHandshakeInterval);
            logger.Info("Recycled Cache Max Count: {0}", _config.RecycledCacheMaxCount);
            logger.Info("UseMessageRecycling: {0}", _config.UseMessageRecycling);
            logger.Info("PeerLietener thread status: {0}", _peerListenTask.Status);
            logger.Info("#####Net Peer Listener#####");
            logger.Info("Status: {0}", _listener.Status);
            logger.Info("Unique Identifier: {0}", _listener.UniqueIdentifier);
            logger.Info("Tag: {0}", _listener.Tag);
            logger.Info("Connections Count: {0}", _listener.ConnectionsCount);
        }
Example #25
0
        private static void StartServer()
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MMO");

            config.Port = 8001;
            config.MaximumConnections = 100;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            server = new NetServer(config);
            server.Start();

            Console.ForegroundColor = logColour;
            Console.Write("CLIENTS CONNECTED: " + clientList.Count);
            Console.WriteLine("");
            Console.ForegroundColor = ConsoleColor.White;

            config       = new NetPeerConfiguration("MMO");
            serverClient = new NetClient(config);
            serverClient.Start();
            NetOutgoingMessage message = serverClient.CreateMessage();

            message.Write((byte)1);             //CONNECT
            serverClient.Connect("127.0.0.1", 8002, message);

            Thread thread = new Thread(ConsoleCommand);

            thread.Start();

            var startTimeSpan  = TimeSpan.Zero;
            var periodTimeSpan = TimeSpan.FromSeconds(5);
            var timer          = new Timer((e) => { Ping(); }, null, startTimeSpan, periodTimeSpan);

            while (shutdown == false)
            {
                Rater193.Update();
                Listen();
            }
            Rater193.Shutdown();

            serverClient.Disconnect("Quit");
            Thread.Sleep(250);
            Environment.Exit(0);
        }
Example #26
0
        public void StartServer()
        {
            SetOnline();
            Console.WriteLine("Loading Map..");
            mapLoader.LoadMap();
            Console.WriteLine("Starting Server.");
            serverConfig = new NetPeerConfiguration(ServerInfo.APPIDENTIFIER);
            serverConfig.MaximumConnections = 100;
            serverConfig.Port = serverPort;
            serverConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            serverConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            server = new NetServer(serverConfig);
            server.Start();


            running = true;

            if (server.Status == NetPeerStatus.Running)
            {
                serverTest  = "Server is Running!";
                label2.Text = serverTest;
                Console.WriteLine("----------");
                Console.WriteLine();
                Console.WriteLine("Server started.");
                Console.WriteLine();
                Console.WriteLine(String.Format("Name: {0}", serverName));
                Console.WriteLine(String.Format("Port: {0}", serverPort));
                Console.WriteLine();
                Console.WriteLine("----------");
                button2.Text    = "Server ONLINE";
                button2.Enabled = false;
                button1.Enabled = true;
            }
            else
            {
                Console.WriteLine("Server did not start.");
            }
            BackgroundWorker worker = new BackgroundWorker();

            worker.DoWork += ServerManager;
            worker.RunWorkerAsync();
        }
Example #27
0
        public bool Connect(string ip, int port, string hailMessage, string appName)
        {
            if (isConnected)
            {
                this.Disconnect();
            }

            NetPeerConfiguration config = new NetPeerConfiguration(appName);

            config.AcceptIncomingConnections = false;

            if (ip == null || appName == null || ip.Length == 0)
            {
                ClassLogger.LogError("Connection to remote host must have a valid appname and IP address.");
#if UNITYDEBUG || UNITYRELEASE
                return(false);
#else
                throw new NullReferenceException("Connection to remote host must have a valid appname and IP address.");
#endif
            }

            //This should reduce GC which is always terrible for Unity.
            config.UseMessageRecycling = true;

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

            NetOutgoingMessage msg = GenerateClientHail(hailMessage);

            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);

            NetConnection connection = internalLidgrenClient.Connect(endPoint, msg);

            this.SetConnectionDetails(connection, endPoint, connection.RemoteUniqueIdentifier);

            _isConnected = true;

            Interlocked.Exchange(ref timeNowByPoll, NetTime.Now < 3 ? 0 : NetTime.Now);
            Interlocked.Exchange(ref timeNowByPollComparer, NetTime.Now < 3 ? 0 : NetTime.Now);

            return(true);
        }
Example #28
0
        public PentagoNetwork(string playerName)
        {
            lastPingTime = DateTime.Now;
            nextPingTime = lastPingTime.AddSeconds(1);

            availablePeers = new List <peerType>();

            config = new NetPeerConfiguration("Pentago");
            // Enable DiscoveryResponse messages
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);
            config.EnableMessageType(NetIncomingMessageType.Data);
            config.ConnectionTimeout         = 5;
            config.AcceptIncomingConnections = true;
            config.MaximumConnections        = 32;
            config.Port = PORT_NUMBER;

            peer = new NetPeer(config);
            try
            {
                peer.Start();
                peerOn = true;

                Console.WriteLine("Peer Started");


                Thread t = new Thread(waitForMessages);
                t.SetApartmentState(ApartmentState.STA);
                peerName = playerName;
                t.Start();

                Console.WriteLine(peerName);

                peer.DiscoverLocalPeers(PORT_NUMBER);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Caught exception: " + ex.Data);
            }
        }
        /// <summary>
        /// The connect.
        /// </summary>
        public void Connect()
        {
            var config = new NetPeerConfiguration("Asteroid")
            {
                SimulatedMinimumLatency = 0.2f,
                // SimulatedLoss = 0.1f
            };

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

            this.netClient = new NetClient(config);
            this.netClient.Start();

            this.netClient.Connect(new IPEndPoint(NetUtility.Resolve("127.0.0.1"), Convert.ToInt32("14242")));
        }
Example #30
0
        public OnlineStuff(Game1 game_)
        {
            game = game_;

            peerConfig = new NetPeerConfiguration("TestGame");
            peerConfig.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            peerConfig.EnableMessageType(NetIncomingMessageType.DiscoveryRequest);
            peerConfig.EnableMessageType(NetIncomingMessageType.Data);
            peerConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            peerConfig.EnableMessageType(NetIncomingMessageType.StatusChanged);
            peerConfig.EnableMessageType(NetIncomingMessageType.DebugMessage);
            peerConfig.EnableMessageType(NetIncomingMessageType.WarningMessage);
            peerConfig.AcceptIncomingConnections = true;
            peerConfig.Port = 8000;
            peer            = new NetPeer(peerConfig);
            peer.Start();
            connecting = false;
            isServer   = false;
            ipId       = new IPID();
        }
 /// <summary>
 /// NetServer constructor
 /// </summary>
 public NetServer(NetPeerConfiguration config)
     : base(config)
 {
     config.AcceptIncomingConnections = true;
 }
 internal NetConnection(NetPeer peer, IPEndPoint remoteEndPoint)
 {
     m_peer = peer;
     m_peerConfiguration = m_peer.Configuration;
     m_status = 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;
 }
 /// <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<IPEndPoint, NetOutgoingMessage>>(2);
     m_connections = new List<NetConnection>();
     m_connectionLookup = new Dictionary<IPEndPoint, NetConnection>();
     m_handshakes = new Dictionary<IPEndPoint, NetConnection>();
     m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
     m_status = NetPeerStatus.NotRunning;
     m_receivedFragmentGroups = new Dictionary<NetConnection, Dictionary<int, ReceivedFragmentGroup>>();
 }
 /// <summary>
 /// NetClient constructor
 /// </summary>
 /// <param name="config"></param>
 public NetClient(NetPeerConfiguration config)
     : base(config)
 {
     config.AcceptIncomingConnections = false;
 }