コード例 #1
0
ファイル: Program.cs プロジェクト: sampad1370/lidgren-network
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            s_nextPixelToSend = new Dictionary <NetConnection, uint>();

            NetConfiguration config = new NetConfiguration("imageservice");

            config.Port                   = 14242;
            config.MaxConnections         = 64;
            config.ThrottleBytesPerSecond = 25000;
            s_server = new NetServer(config);
            s_server.SimulatedMinimumLatency = 0.05f;
            s_server.SimulatedLoss           = m_loss;
            s_fpsStart = NetTime.Now;

            s_readBuffer = s_server.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_server.Shutdown("Application exit");
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: sampad1370/lidgren-network
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("stress");

            config.ThrottleBytesPerSecond = 3500;

            s_client = new NetClient(config);

            // 100 ms simulated roundtrip latency
            s_client.SimulatedMinimumLatency = 0.1f;

            // ... + 0 to 50 ms
            s_client.SimulatedLatencyVariance = 0.05f;

            // 10% loss (!)
            //	s_client.SimulatedLoss = 0.1f;

            // 5% duplicated messages (!)
            //	s_client.SimulatedDuplicates = 0.05f;

            s_readBuffer = s_client.CreateBuffer();

            s_sentUntil   = NetTime.Now;
            s_nextDisplay = NetTime.Now;

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_client.Shutdown("Application exiting");
        }
コード例 #3
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            WriteToConsole("Type 'connect <host> <port>' to connect to another peer, or 'connect <port>' to connect to another localhost peer");

            NetConfiguration config = new NetConfiguration("p2pchat");

            config.MaxConnections = 256;
            s_peer = new NetPeer(config);
            //s_peer.VerboseLog = true;

            s_peer.SetMessageTypeEnabled(NetMessageType.ConnectionRejected | NetMessageType.BadMessageReceived | NetMessageType.VerboseDebugMessage, true);

            // start listening for incoming connections
            s_peer.Start();

            // create a buffer to read data into
            s_readBuffer = s_peer.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_peer.Shutdown("Application exiting");
        }
コード例 #4
0
        protected ProxyApi(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration,
                           CommonConfiguration commonConfiguration, TimeoutConfiguration timeoutConfiguration)
        {
            Contract.Requires(netConfiguration != null);
            Contract.Requires(proxyConfiguration != null);
            Contract.Requires(commonConfiguration != null);
            Contract.Requires(timeoutConfiguration != null);

            _isStarted = false;
            _isBuild   = false;
            _isDispose = false;

            var server = new ServerId(netConfiguration.Host, netConfiguration.Port);
            var queue  = new QueueConfiguration(commonConfiguration.CountThreads, commonConfiguration.QueueSize);

            var connection = new ConnectionConfiguration(netConfiguration.WcfServiceName,
                                                         netConfiguration.CountConnectionsToSingleServer);
            var proxyCacheConfiguration  = new ProxyCacheConfiguration(proxyConfiguration.ChangeDistributorTimeoutSec);
            var proxyCacheConfiguration2 = new ProxyCacheConfiguration(proxyConfiguration.SyncOperationsTimeoutSec);
            var netReceiveConfiguration  = new NetReceiverConfiguration(netConfiguration.Port, netConfiguration.Host,
                                                                        netConfiguration.WcfServiceName);
            var async   = new AsyncTasksConfiguration(proxyConfiguration.AsyncUpdateTimeout);
            var ping    = new AsyncTasksConfiguration(proxyConfiguration.AsyncPingTimeout);
            var timeout = new ConnectionTimeoutConfiguration(timeoutConfiguration.OpenTimeout,
                                                             timeoutConfiguration.SendTimeout);

            _proxySystem = new ProxySystem(server, queue, connection,
                                           proxyCacheConfiguration, proxyCacheConfiguration2, netReceiveConfiguration, async, ping, timeout);

            _apis = new Dictionary <string, ProxyHandlerBase>();
        }
コード例 #5
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("largepacket");

            config.Port           = 14242;
            config.MaxConnections = 16;
            s_server = new NetServer(config);
            s_server.SimulatedLoss            = 0.03f;  // 3 %
            s_server.SimulatedMinimumLatency  = 0.1f;   // 100 ms
            s_server.SimulatedLatencyVariance = 0.05f;  // 100-150 ms actually

            //m_server.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            s_server.Start();

            s_readBuffer = s_server.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_server.Shutdown("Application exiting");
        }
コード例 #6
0
ファイル: TeslaForm.cs プロジェクト: Aattiiff/TeslaAutomation
        private void SbStart_Click(object sender, EventArgs e)
        {
            if (!NetConfiguration.PingTest())
            {
                XtraMessageBox.Show("Please connect to internet.");
                SbStart.Focus();
                return;
            }

            if (string.IsNullOrEmpty(TeURL.Text))
            {
                XtraMessageBox.Show("Please enter URL.");
                TeURL.Focus();
                return;
            }

            SbStart.Enabled = false;
            if (BwStart.IsBusy)
            {
                BwStart.CancelAsync();
            }
            else
            {
                BwStart.RunWorkerAsync();
            }
            PgrsPanel.Show();
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: sampad1370/lidgren-network
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            m_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("largepacket");

            config.SendBufferSize         = 128000;
            config.ThrottleBytesPerSecond = 8192;
            m_client = new NetClient(config);
            m_client.SimulatedLoss            = 0.03f;  // 3 %
            m_client.SimulatedMinimumLatency  = 0.1f;   // 100 ms
            m_client.SimulatedLatencyVariance = 0.05f;  // 100-150 ms actually

            //m_client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            m_client.SetMessageTypeEnabled(NetMessageType.Receipt, true);

            m_readBuffer = m_client.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(m_mainForm);

            m_client.Shutdown("Application exiting");
        }
コード例 #8
0
 public void Dispose()
 {
     NetConfiguration.Dispose();
     AudioConfig.Dispose();
     Config           = null;
     NetConfiguration = null;
     AudioConfig      = null;
     _config          = null;
 }
コード例 #9
0
        public void Initialize()
        {
            var common = new CommonConfiguration(1, 100);

            var netconfig = new NetConfiguration("localhost", proxyServer, "testService", 10);
            var toconfig  = new ProxyConfiguration(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1),
                                                   TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));

            _proxy = new TestGate(netconfig, toconfig, common);
            _proxy.Build();
        }
コード例 #10
0
ファイル: Server.cs プロジェクト: KoalaDack/SteamDramaBot
 public void start(string name, int connections, int port)
 {
     //Create configuration.
     config = new NetConfiguration(name);
     config.MaxConnections = connections;
     config.Port           = port;
     //Create the server!
     server = new NetServer(config);
     server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
     server.Start();
     //Create a buffer.
     readBuffer = server.CreateBuffer();
     Debug.PrintEvent("Server is running! press escape to exit server");
     consoleIdle(true);
 }
コード例 #11
0
 internal static void GetConfig()
 {
     if (s_NetConfig == null)
     {
         lock (typeof(ServicePointManager)) {
             if (s_NetConfig == null)
             {
                 s_NetConfig = (NetConfiguration)ConfigurationSettings.GetConfig("system.net/settings");
             }
             if (s_NetConfig == null)
             {
                 s_NetConfig = new NetConfiguration();
             }
         }
     }
 }
        private void _MasterInit()
        {
            var config = new NetConfiguration(Constants.CONFIG_MASTER_IDENTIFIER);

            config.MaxConnections          = 1;
            config.PingFrequency           = 6F;   //Higher than default 3F to avoid too high load on the master server when there are thousands of clients.
            config.TimeoutDelay            = 60F;
            config.AnswerDiscoveryRequests = false;
            config.SendBufferSize          = Constants.DEFAULT_SEND_BUFFER_SIZE;
            config.ReceiveBufferSize       = Constants.DEFAULT_RECV_BUFFER_SIZE;

            _master = new NetClient(config);
            _ConfigureNetBase(_master);

            _readBuffer = _master.CreateBuffer();
        }
コード例 #13
0
        public ImageClient()
        {
            InitializeComponent();

            NetConfiguration config = new NetConfiguration("imageservice");

            m_client = new NetClient(config);
            m_client.SimulatedMinimumLatency = 0.05f;

            m_readBuffer = m_client.CreateBuffer();

            m_client.DiscoverLocalServers(14242);

            this.FormClosed += new FormClosedEventHandler(OnClosed);
            this.Show();
        }
コード例 #14
0
        public virtual object Create(Object parent, object configContext, XmlNode section)
        {
            NetConfiguration netConfig;

            if (parent == null)
            {
                netConfig = new NetConfiguration();
            }
            else
            {
                netConfig = (NetConfiguration)((NetConfiguration)parent).Clone();
            }

            // process XML
            foreach (XmlNode child in section.ChildNodes)
            {
                // skip whitespace and comments
                if (HandlerBase.IsIgnorableAlsoCheckForNonElement(child))
                {
                    continue;
                }

                switch (child.Name)
                {
                case "servicePointManager":
                    HandlerBase.GetAndRemoveBooleanAttribute(child, "checkCertificateName", ref netConfig.checkCertName);
                    HandlerBase.GetAndRemoveBooleanAttribute(child, "checkCertificateRevocationList", ref netConfig.checkCertRevocationList);
                    HandlerBase.GetAndRemoveBooleanAttribute(child, "useNagleAlgorithm", ref netConfig.useNagleAlgorithm);
                    HandlerBase.GetAndRemoveBooleanAttribute(child, "expect100Continue", ref netConfig.expect100Continue);
                    break;

                case "ipv6":
                    HandlerBase.GetAndRemoveBooleanAttribute(child, "enabled", ref netConfig.ipv6Enabled);
                    break;

                case "httpWebRequest":
                    HandlerBase.GetAndRemoveIntegerAttribute(child, "maximumResponseHeadersLength", ref netConfig.maximumResponseHeadersLength);
                    break;

                default:
                    HandlerBase.ThrowUnrecognizedElement(child);
                    break;
                }
                HandlerBase.CheckForUnrecognizedAttributes(child);
            }
            return(netConfig);
        }
コード例 #15
0
        public PropertyBag(InfiniminerGame gameInstance)
        {
            // Initialize our network device.
            NetConfiguration netConfig = new NetConfiguration("InfiniminerPlus");

            netClient = new NetClient(netConfig);
            netClient.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, 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");
            }
        }
コード例 #16
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("OoBSample");

            s_client = new NetClient(config);
            s_client.SetMessageTypeEnabled(NetMessageType.OutOfBandData, true);
            s_client.Start();

            s_readBuffer = s_client.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_client.Shutdown("Bye");
        }
コード例 #17
0
        public static void setupNetwork()
        {
            NetConfiguration config = new NetConfiguration("apache");

            client = new NetClient(config);
            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
            //client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.Start();

            // Wait half a second to allow server to start up if run via Visual Studio
            Thread.Sleep(500);

            // Emit discovery signal
            //client.DiscoverLocalServers(14242);
            client.Connect("127.0.0.1", 14242, Encoding.ASCII.GetBytes("Hail from client"));


            Thread.Sleep(500);
        }
コード例 #18
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("OoBSample");

            config.MaxConnections = 0;             // we accept only OoB data
            config.Port           = 14242;
            s_server = new NetServer(config);
            s_server.SetMessageTypeEnabled(NetMessageType.OutOfBandData, true);
            s_server.Start();

            s_readBuffer = s_server.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_server.Shutdown("Bye");
        }
コード例 #19
0
ファイル: LoginForm.cs プロジェクト: Aattiiff/TeslaAutomation
        private void SbLogin_Click(object sender, EventArgs e)
        {
            if (!NetConfiguration.PingTest())
            {
                XtraMessageBox.Show("Please connect to internet.");
                SbLogin.Focus();
                return;
            }

            SbLogin.Enabled = false;
            if (IsFormValidated(SbLogin))
            {
                if (BwLogin.IsBusy)
                {
                    BwLogin.CancelAsync();
                }
                else
                {
                    BwLogin.RunWorkerAsync();
                }
                PpWait.Show();
            }
        }
コード例 #20
0
        public void Initialize()
        {
            var common   = new CommonConfiguration(1, 100);
            var distrNet = new DistributorNetConfiguration("localhost",
                                                           distrServer1, distrServer12, "testService", 10);
            var distrConf = new DistributorConfiguration(1, "TestRestore",
                                                         TimeSpan.FromMilliseconds(10000000), TimeSpan.FromMilliseconds(500000), TimeSpan.FromMinutes(100),
                                                         TimeSpan.FromMilliseconds(10000000));

            _distr = new DistributorApi(distrNet, distrConf, common);
            _distr.Build();

            var netconfig = new NetConfiguration("localhost", proxyServer, "testService", 10);
            var toconfig  = new ProxyConfiguration(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1),
                                                   TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));

            _proxy = new TestGate(netconfig, toconfig, common);
            _proxy.Build();

            _distrTest = new TestDistributorGate();
            _writer1   = new TestWriterGate();
            _writer2   = new TestWriterGate();
            _writer3   = new TestWriterGate();
        }
コード例 #21
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            s_mainForm = new Form1();

            NetConfiguration config = new NetConfiguration("stress");

            config.Port           = 14242;
            config.MaxConnections = 32;
            s_server = new NetServer(config);

            s_server.SimulatedMinimumLatency  = 0.1f;
            s_server.SimulatedLatencyVariance = 0.05f;
//			s_server.SimulatedLoss = 0.1f;
//			s_server.SimulatedDuplicates = 0.05f;

            s_readBuffer = s_server.CreateBuffer();

            Application.Idle += new EventHandler(OnAppIdle);
            Application.Run(s_mainForm);

            s_server.Shutdown("Application exiting");
        }
コード例 #22
0
 public TestGate(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration,
                 CommonConfiguration commonConfiguration)
     : base(netConfiguration, proxyConfiguration, commonConfiguration)
 {
 }
コード例 #23
0
        public void CollectorNet_ReadFromWriter()
        {
            const int proxyServer   = 22337;
            const int distrServer1  = 22338;
            const int distrServer12 = 22339;
            const int st1           = 22335;
            const int st2           = 22336;

            #region hell

            var writer = new HashWriter(new HashMapConfiguration("TestCollectorNet", HashMapCreationMode.CreateNew, 1, 1, HashFileType.Distributor));
            writer.CreateMap();
            writer.SetServer(0, "localhost", st1, st2);
            writer.Save();

            var common = new CommonConfiguration(1, 100);

            var netconfig = new NetConfiguration("localhost", proxyServer, "testService", 10);
            var toconfig  = new ProxyConfiguration(TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(1),
                                                   TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10));

            var proxy = new TestGate(netconfig, toconfig, common);

            var distrNet = new DistributorNetConfiguration("localhost",
                                                           distrServer1, distrServer12, "testService", 10);
            var distrConf = new DistributorConfiguration(1, "TestCollectorNet",
                                                         TimeSpan.FromMilliseconds(100000), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(10000));

            var distr = new DistributorApi(distrNet, distrConf, common);

            var storageNet    = new StorageNetConfiguration("localhost", st1, st2, "testService", 10);
            var storageConfig = new StorageConfiguration("TestCollectorNet", 1, 10, TimeSpan.FromHours(1), TimeSpan.FromHours(1),
                                                         TimeSpan.FromHours(1), TimeSpan.FromHours(1), false);

            var storage     = new WriterApi(storageNet, storageConfig, common);
            var async       = new AsyncTaskModule(new QueueConfiguration(4, 10));
            var distributor =
                new DistributorModule(new CollectorModel(new DistributorHashConfiguration(1),
                                                         new HashMapConfiguration("TestCollectorNet", HashMapCreationMode.ReadFromFile, 1, 1,
                                                                                  HashFileType.Collector)), async, new AsyncTasksConfiguration(TimeSpan.FromMinutes(1)));

            var net = new CollectorNetModule(new ConnectionConfiguration("testService", 10),
                                             new ConnectionTimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout), distributor);

            distributor.SetNetModule(net);

            var back   = new BackgroundModule(new QueueConfiguration(5, 10));
            var loader = new DataLoader(net, 100, back);

            var parser = new TestIntParser();
            parser.SetCommandsHandler(
                new UserCommandsHandler <TestCommand, Type, TestCommand, int, int, TestDbReader>(
                    new TestUserCommandCreator(), new TestMetaDataCommandCreator()));
            var merge = new OrderMerge(loader, parser);

            var searchModule = new SearchTaskModule("Int", merge, loader, distributor, back, parser);

            storage.Build();
            proxy.Build();
            distr.Build();

            storage.AddDbModule(new TestInMemoryDbFactory());

            storage.Start();
            proxy.Start();
            distr.Start();

            searchModule.Start();
            distributor.Start();
            merge.Start();
            back.Start();
            net.Start();
            async.Start();

            #endregion

            proxy.Int.SayIAmHere("localhost", distrServer1);

            const int count = 20;

            for (int i = 0; i < count; i++)
            {
                var request = proxy.Int.CreateSync(i, i);
                Assert.AreEqual(RequestState.Complete, request.State);
            }

            var reader = searchModule.CreateReader("asc", -1, 20);
            reader.Start();

            for (int i = 0; i < count; i++)
            {
                Assert.IsTrue(reader.IsCanRead);

                reader.ReadNext();

                Assert.AreEqual(i, reader.GetValue(0));
            }
            reader.ReadNext();
            Assert.IsFalse(reader.IsCanRead);

            reader.Dispose();
            back.Dispose();
            net.Dispose();

            storage.Dispose();
            proxy.Dispose();
            distr.Dispose();
            async.Dispose();
        }
コード例 #24
0
        static void Main(string[] args)
        {
            // create a client with a default configuration
            NetConfiguration config = new NetConfiguration("chatApp");
            NetClient        client = new NetClient(config);

            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);
            client.SetMessageTypeEnabled(NetMessageType.DebugMessage, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.Start();

            // Wait half a second to allow server to start up if run via Visual Studio
            Thread.Sleep(500);

            // Emit discovery signal
            client.DiscoverLocalServers(14242);

            // create a buffer to read data into
            NetBuffer buffer = client.CreateBuffer();

            // current input string
            string input = "";

            // keep running until the user presses a key
            Console.WriteLine("Type 'quit' to exit client");
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            s_keepGoing             = true;
            while (s_keepGoing)
            {
                NetMessageType type;

                // check if any messages has been received
                while (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                    case NetMessageType.ServerDiscovered:
                        // just connect to any server found!

                        // make hail
                        NetBuffer buf = client.CreateBuffer();
                        buf.Write("Hail from " + Environment.MachineName);
                        client.Connect(buffer.ReadIPEndPoint(), buf.ToArray());
                        break;

                    case NetMessageType.ConnectionRejected:
                        Console.WriteLine("Rejected: " + buffer.ReadString());
                        break;

                    case NetMessageType.DebugMessage:
                    case NetMessageType.VerboseDebugMessage:
                        Console.WriteLine(buffer.ReadString());
                        break;

                    case NetMessageType.StatusChanged:
                        string statusMessage          = buffer.ReadString();
                        NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
                        Console.WriteLine("New status: " + newStatus + " (" + statusMessage + ")");
                        break;

                    case NetMessageType.Data:
                        // The server sent this data!
                        string msg = buffer.ReadString();
                        Console.WriteLine(msg);
                        break;
                    }
                }

                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo ki = Console.ReadKey();
                    if (ki.Key == ConsoleKey.Enter)
                    {
                        if (!string.IsNullOrEmpty(input))
                        {
                            if (input == "quit")
                            {
                                // exit application
                                s_keepGoing = false;
                            }
                            else
                            {
                                // Send chat message
                                NetBuffer sendBuffer = new NetBuffer();
                                sendBuffer.Write(input);
                                client.SendMessage(sendBuffer, NetChannel.ReliableInOrder1);
                                input = "";
                            }
                        }
                    }
                    else
                    {
                        input += ki.KeyChar;
                    }
                }

                Thread.Sleep(1);
            }

            client.Shutdown("Application exiting");
        }
コード例 #25
0
        static void Main(string[] args)
        {
            // create a configuration for the server
            NetConfiguration config = new NetConfiguration("chatApp");

            config.MaxConnections = 128;
            config.Port           = 14242;

            // create server and start listening for connections
            NetServer server = new NetServer(config);

            server.SetMessageTypeEnabled(NetMessageType.ConnectionApproval, true);
            server.Start();

            // create a buffer to read data into
            NetBuffer buffer = server.CreateBuffer();

            // keep running until the user presses a key
            Console.WriteLine("Press ESC to quit server");
            bool keepRunning = true;

            while (keepRunning)
            {
                NetMessageType type;
                NetConnection  sender;

                // check if any messages has been received
                while (server.ReadMessage(buffer, out type, out sender))
                {
                    switch (type)
                    {
                    case NetMessageType.DebugMessage:
                        Console.WriteLine(buffer.ReadString());
                        break;

                    case NetMessageType.ConnectionApproval:
                        Console.WriteLine("Approval; hail is " + buffer.ReadString());
                        sender.Approve();
                        break;

                    case NetMessageType.StatusChanged:
                        string statusMessage          = buffer.ReadString();
                        NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
                        Console.WriteLine("New status for " + sender + ": " + newStatus + " (" + statusMessage + ")");
                        break;

                    case NetMessageType.Data:
                        // A client sent this data!
                        string msg = buffer.ReadString();

                        // send to everyone, including sender
                        NetBuffer sendBuffer = server.CreateBuffer();
                        sendBuffer.Write(sender.RemoteEndpoint.ToString() + " wrote: " + msg);

                        // send using ReliableInOrder
                        server.SendToAll(sendBuffer, NetChannel.ReliableInOrder1);
                        break;
                    }
                }

                // User pressed ESC?
                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo info = Console.ReadKey();
                    if (info.Key == ConsoleKey.Escape)
                    {
                        keepRunning = false;
                    }
                }

                Thread.Sleep(1);
            }

            server.Shutdown("Application exiting");
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: sampad1370/lidgren-network
        static unsafe void Main(string[] args)
        {
            // JIT stuff
            NetBuffer msg = new NetBuffer(20);

            msg.Write((short)short.MaxValue);

            // Go
            double timeStart = NetTime.Now;

            msg = new NetBuffer(20);
            for (int n = 0; n < 10000; n++)
            {
                msg.Reset();

                msg.Write((short)short.MaxValue);
                msg.Write((short)short.MinValue);
                msg.Write((short)-42);

                msg.Write(421);
                msg.Write((byte)7);
                msg.Write(-42.8f);

                if (msg.LengthBytes != 15)
                {
                    throw new Exception("Bad message length");
                }

                msg.Write("duke of earl");

                int bytesWritten;
                bytesWritten = msg.WriteVariableInt32(-1);
                bytesWritten = msg.WriteVariableInt32(5);
                bytesWritten = msg.WriteVariableInt32(-18);
                bytesWritten = msg.WriteVariableInt32(42);
                bytesWritten = msg.WriteVariableInt32(-420);

                msg.Write((uint)9991);

                // byte boundary kept until here

                msg.Write(true);
                msg.Write((uint)3, 5);
                msg.Write(8.111f);
                msg.Write("again");
                byte[] arr = new byte[] { 1, 6, 12, 24 };
                msg.Write(arr);
                msg.Write((byte)7, 7);
                msg.Write(Int32.MinValue);
                msg.Write(UInt32.MaxValue);
                msg.WriteRangedSingle(21.0f, -10, 50, 12);

                // test reduced bit signed writing
                msg.Write(15, 5);
                msg.Write(2, 5);
                msg.Write(0, 5);
                msg.Write(-1, 5);
                msg.Write(-2, 5);
                msg.Write(-15, 5);

                msg.Write(UInt64.MaxValue);
                msg.Write(Int64.MaxValue);
                msg.Write(Int64.MinValue);

                msg.Write(42);
                msg.WritePadBits();

                int numBits = msg.WriteRangedInteger(0, 10, 5);
                if (numBits != 4)
                {
                    throw new Exception("Ack WriteRangedInteger failed");
                }

                // verify
                msg.Position = 0;

                short a = msg.ReadInt16();
                short b = msg.ReadInt16();
                short c = msg.ReadInt16();

                if (a != short.MaxValue || b != short.MinValue || c != -42)
                {
                    throw new Exception("Ack thpth short failed");
                }

                if (msg.ReadInt32() != 421)
                {
                    throw new Exception("Ack thphth 1");
                }
                if (msg.ReadByte() != (byte)7)
                {
                    throw new Exception("Ack thphth 2");
                }
                if (msg.ReadSingle() != -42.8f)
                {
                    throw new Exception("Ack thphth 3");
                }
                if (msg.ReadString() != "duke of earl")
                {
                    throw new Exception("Ack thphth 4");
                }

                if (msg.ReadVariableInt32() != -1)
                {
                    throw new Exception("ReadVariableInt32 failed 1");
                }
                if (msg.ReadVariableInt32() != 5)
                {
                    throw new Exception("ReadVariableInt32 failed 2");
                }
                if (msg.ReadVariableInt32() != -18)
                {
                    throw new Exception("ReadVariableInt32 failed 3");
                }
                if (msg.ReadVariableInt32() != 42)
                {
                    throw new Exception("ReadVariableInt32 failed 4");
                }
                if (msg.ReadVariableInt32() != -420)
                {
                    throw new Exception("ReadVariableInt32 failed 5");
                }

                if (msg.ReadUInt32() != 9991)
                {
                    throw new Exception("Ack thphth 4.5");
                }

                if (msg.ReadBoolean() != true)
                {
                    throw new Exception("Ack thphth 5");
                }
                if (msg.ReadUInt32(5) != (uint)3)
                {
                    throw new Exception("Ack thphth 6");
                }
                if (msg.ReadSingle() != 8.111f)
                {
                    throw new Exception("Ack thphth 7");
                }
                if (msg.ReadString() != "again")
                {
                    throw new Exception("Ack thphth 8");
                }
                byte[] rrr = msg.ReadBytes(4);
                if (rrr[0] != arr[0] || rrr[1] != arr[1] || rrr[2] != arr[2] || rrr[3] != arr[3])
                {
                    throw new Exception("Ack thphth 9");
                }
                if (msg.ReadByte(7) != 7)
                {
                    throw new Exception("Ack thphth 10");
                }
                if (msg.ReadInt32() != Int32.MinValue)
                {
                    throw new Exception("Ack thphth 11");
                }
                if (msg.ReadUInt32() != UInt32.MaxValue)
                {
                    throw new Exception("Ack thphth 12");
                }

                float v = msg.ReadRangedSingle(-10, 50, 12);
                // v should be close to, but not necessarily exactly, 21.0f
                if ((float)Math.Abs(21.0f - v) > 0.1f)
                {
                    throw new Exception("Ack thphth *RangedSingle() failed");
                }

                if (msg.ReadInt32(5) != 15)
                {
                    throw new Exception("Ack thphth ReadInt32 1");
                }
                if (msg.ReadInt32(5) != 2)
                {
                    throw new Exception("Ack thphth ReadInt32 2");
                }
                if (msg.ReadInt32(5) != 0)
                {
                    throw new Exception("Ack thphth ReadInt32 3");
                }
                if (msg.ReadInt32(5) != -1)
                {
                    throw new Exception("Ack thphth ReadInt32 4");
                }
                if (msg.ReadInt32(5) != -2)
                {
                    throw new Exception("Ack thphth ReadInt32 5");
                }
                if (msg.ReadInt32(5) != -15)
                {
                    throw new Exception("Ack thphth ReadInt32 6");
                }

                UInt64 longVal = msg.ReadUInt64();
                if (longVal != UInt64.MaxValue)
                {
                    throw new Exception("Ack thphth UInt64");
                }
                if (msg.ReadInt64() != Int64.MaxValue)
                {
                    throw new Exception("Ack thphth Int64");
                }
                if (msg.ReadInt64() != Int64.MinValue)
                {
                    throw new Exception("Ack thphth Int64");
                }

                if (msg.ReadInt32() != 42)
                {
                    throw new Exception("Ack thphth end");
                }

                msg.SkipPadBits();

                if (msg.ReadRangedInteger(0, 10) != 5)
                {
                    throw new Exception("Ack thphth ranged integer");
                }
            }

            // test writevariableuint64
            NetBuffer largeBuffer = new NetBuffer(100 * 8);

            UInt64[] largeNumbers = new ulong[100];
            for (int i = 0; i < 100; i++)
            {
                largeNumbers[i] = ((ulong)NetRandom.Instance.NextUInt() << 32) | (ulong)NetRandom.Instance.NextUInt();
                largeBuffer.WriteVariableUInt64(largeNumbers[i]);
            }

            largeBuffer.Position = 0;
            for (int i = 0; i < 100; i++)
            {
                UInt64 ln = largeBuffer.ReadVariableUInt64();
                if (ln != largeNumbers[i])
                {
                    throw new Exception("large fail");
                }
            }

            //
            // Extended tests on padbits
            //
            for (int i = 1; i < 31; i++)
            {
                NetBuffer buf = new NetBuffer();
                buf.Write((int)1, i);

                if (buf.LengthBits != i)
                {
                    throw new Exception("Bad length!");
                }

                buf.WritePadBits();
                int wholeBytes = buf.LengthBits / 8;
                if (wholeBytes * 8 != buf.LengthBits)
                {
                    throw new Exception("WritePadBits failed! Length is " + buf.LengthBits);
                }
            }

            NetBuffer small = new NetBuffer(100);

            byte[] rnd  = new byte[24];
            int[]  bits = new int[24];
            for (int i = 0; i < 24; i++)
            {
                rnd[i]  = (byte)NetRandom.Instance.Next(0, 65);
                bits[i] = NetUtility.BitsToHoldUInt((uint)rnd[i]);

                small.Write(rnd[i], bits[i]);
            }

            small.Position = 0;
            for (int i = 0; i < 24; i++)
            {
                byte got = small.ReadByte(bits[i]);
                if (got != rnd[i])
                {
                    throw new Exception("Failed small allocation test");
                }
            }

            double timeEnd  = NetTime.Now;
            double timeSpan = timeEnd - timeStart;

            Console.WriteLine("Trivial tests passed in " + (timeSpan * 1000.0) + " milliseconds");

            Console.WriteLine("Creating client and server for live testing...");

            NetConfiguration config = new NetConfiguration("unittest");

            config.Port = 14242;
            NetServer server       = new NetServer(config);
            NetBuffer serverBuffer = new NetBuffer();

            server.Start();

            config = new NetConfiguration("unittest");
            NetClient client = new NetClient(config);

            client.SetMessageTypeEnabled(NetMessageType.Receipt, true);
            NetBuffer clientBuffer = client.CreateBuffer();

            client.Start();

            client.Connect("127.0.0.1", 14242);

            List <string> events = new List <string>();

            double end        = double.MaxValue;
            double disconnect = double.MaxValue;

            while (NetTime.Now < end)
            {
                double now = NetTime.Now;

                NetMessageType nmt;
                NetConnection  sender;

                //
                // client
                //
                if (client.ReadMessage(clientBuffer, out nmt))
                {
                    switch (nmt)
                    {
                    case NetMessageType.StatusChanged:
                        Console.WriteLine("Client: " + client.Status + " (" + clientBuffer.ReadString() + ")");
                        events.Add("CStatus " + client.Status);
                        if (client.Status == NetConnectionStatus.Connected)
                        {
                            // send reliable message
                            NetBuffer buf = client.CreateBuffer();
                            buf.Write(true);
                            buf.Write((int)52, 7);
                            buf.Write("Hallon");

                            client.SendMessage(buf, NetChannel.ReliableInOrder1, new NetBuffer("kokos"));
                        }

                        if (client.Status == NetConnectionStatus.Disconnected)
                        {
                            end = NetTime.Now + 1.0;                                     // end in one second
                        }
                        break;

                    case NetMessageType.Receipt:
                        events.Add("CReceipt " + clientBuffer.ReadString());
                        break;

                    case NetMessageType.ConnectionRejected:
                    case NetMessageType.BadMessageReceived:
                        throw new Exception("Failed: " + nmt);

                    case NetMessageType.DebugMessage:
                        // silently ignore
                        break;

                    default:
                        // ignore
                        Console.WriteLine("Ignored: " + nmt);
                        break;
                    }
                }

                //
                // server
                //
                if (server.ReadMessage(serverBuffer, out nmt, out sender))
                {
                    switch (nmt)
                    {
                    case NetMessageType.StatusChanged:
                        events.Add("SStatus " + sender.Status);
                        Console.WriteLine("Server: " + sender.Status + " (" + serverBuffer.ReadString() + ")");
                        break;

                    case NetMessageType.ConnectionRejected:
                    case NetMessageType.BadMessageReceived:
                        throw new Exception("Failed: " + nmt);

                    case NetMessageType.Data:
                        events.Add("DataRec " + serverBuffer.LengthBits);
                        bool   shouldBeTrue     = serverBuffer.ReadBoolean();
                        int    shouldBeFifthTwo = serverBuffer.ReadInt32(7);
                        string shouldBeHallon   = serverBuffer.ReadString();

                        if (shouldBeTrue != true ||
                            shouldBeFifthTwo != 52 ||
                            shouldBeHallon != "Hallon")
                        {
                            throw new Exception("Bad data transmission");
                        }

                        disconnect = now + 1.0;
                        break;

                    case NetMessageType.DebugMessage:
                        // silently ignore
                        break;

                    default:
                        // ignore
                        Console.WriteLine("Ignored: " + nmt);
                        break;
                    }
                }

                if (now > disconnect)
                {
                    server.Connections[0].Disconnect("Bye", 0.1f);
                    disconnect = double.MaxValue;
                }
            }

            // verify events
            string[] expected = new string[] {
                "CStatus Connecting",
                "SStatus Connecting",
                "CStatus Connected",
                "SStatus Connected",
                "DataRec 64",
                "CReceipt kokos",
                "SStatus Disconnecting",
                "CStatus Disconnecting",
                "SStatus Disconnected",
                "CStatus Disconnected"
            };

            if (events.Count != expected.Length)
            {
                throw new Exception("Mismatch in events count! Expected " + expected.Length + ", got " + events.Count);
            }

            for (int i = 0; i < expected.Length; i++)
            {
                if (events[i] != expected[i])
                {
                    throw new Exception("Event " + i + " (" + expected[i] + ") mismatched!");
                }
            }

            Console.WriteLine("All tests successful");

            Console.ReadKey();

            server.Shutdown("App exiting");
            client.Shutdown("App exiting");
        }
コード例 #27
0
        static void Main(string[] args)
        {
            NetConfiguration config = new NetConfiguration("durable");
            NetClient        client = new NetClient(config);

            client.SimulatedMinimumLatency  = 0.05f;
            client.SimulatedLatencyVariance = 0.025f;
            client.SimulatedLoss            = 0.03f;

            // wait half a second to allow server to start up in Visual Studio
            Thread.Sleep(500);

            // create a buffer to read data into
            NetBuffer buffer = client.CreateBuffer();

            // connect to localhost
            client.Connect("127.0.0.1", 14242, Encoding.ASCII.GetBytes("Hail from client"));

            // enable some library messages
            client.SetMessageTypeEnabled(NetMessageType.BadMessageReceived, true);
            //client.SetMessageTypeEnabled(NetMessageType.VerboseDebugMessage, true);
            client.SetMessageTypeEnabled(NetMessageType.ConnectionRejected, true);

            FileStream   fs  = new FileStream("./clientlog.txt", FileMode.Create, FileAccess.Write, FileShare.Read);
            StreamWriter wrt = new StreamWriter(fs);

            Output(wrt, "Log started at " + DateTime.Now);
            wrt.Flush();

            // create a stopwatch
            Stopwatch sw = new Stopwatch();

            sw.Start();
            int loops = 0;

            while (!Console.KeyAvailable)
            {
                NetMessageType type;
                if (client.ReadMessage(buffer, out type))
                {
                    switch (type)
                    {
                    case NetMessageType.StatusChanged:
                        string statusMessage          = buffer.ReadString();
                        NetConnectionStatus newStatus = (NetConnectionStatus)buffer.ReadByte();
                        if (client.ServerConnection.RemoteHailData != null)
                        {
                            Output(wrt, "New status: " + newStatus + " (" + statusMessage + ") Remote hail is: " + Encoding.ASCII.GetString(client.ServerConnection.RemoteHailData));
                        }
                        else
                        {
                            Output(wrt, "New status: " + newStatus + " (" + statusMessage + ") Remote hail hasn't arrived.");
                        }
                        break;

                    case NetMessageType.BadMessageReceived:
                    case NetMessageType.ConnectionRejected:
                    case NetMessageType.DebugMessage:
                    case NetMessageType.VerboseDebugMessage:
                        //
                        // These types of messages all contain a string in the buffer; display it.
                        //
                        Output(wrt, buffer.ReadString());
                        break;

                    case NetMessageType.Data:
                    default:
                        //
                        // For this application; server doesn't send any data... so Data messages are unhandled
                        //
                        Output(wrt, "Unhandled: " + type + " " + buffer.ToString());
                        break;
                    }
                }

                // send a message every second
                if (client.Status == NetConnectionStatus.Connected && sw.Elapsed.TotalMilliseconds >= 516)
                {
                    loops++;
                    //Console.WriteLine("Sending message #" + loops);
                    Console.Title = "Client; Messages sent: " + loops;

                    Output(wrt, "Sending #" + loops + " at " + NetTime.ToMillis(NetTime.Now));
                    NetBuffer send = client.CreateBuffer();
                    send.Write("Message #" + loops);
                    client.SendMessage(send, NetChannel.ReliableInOrder14);

                    sw.Reset();
                    sw.Start();
                }

                Thread.Sleep(1);
            }

            // clean shutdown
            client.Shutdown("Application exiting");
            wrt.Close();
        }
コード例 #28
0
 public RedisGate(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration,
                  CommonConfiguration commonConfiguration, TimeoutConfiguration timeoutConfiguration)
     : base(netConfiguration, proxyConfiguration, commonConfiguration, timeoutConfiguration)
 {
 }
コード例 #29
0
ファイル: NATServer.cs プロジェクト: Microdust/MicroNet
 public NATServer(NetConfiguration config, uint maxHostCount) : base(config)
 {
 }
コード例 #30
0
 protected ProxyApi(NetConfiguration netConfiguration, ProxyConfiguration proxyConfiguration,
                    CommonConfiguration commonConfiguration)
     : this(netConfiguration, proxyConfiguration, commonConfiguration,
            new TimeoutConfiguration(Consts.OpenTimeout, Consts.SendTimeout))
 {
 }