public void UdpUnreliableMessageSendTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    MessageReader output = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs e)
                    {
                        e.Connection.DataReceived += delegate(DataReceivedEventArgs evt)
                        {
                            output = evt.Message;
                        };
                    };

                    listener.Start();
                    connection.Connect();

                    for (int i = 0; i < 4; ++i)
                    {
                        var msg = MessageWriter.Get(SendOption.None);
                        msg.Write(TestData);
                        connection.Send(msg);
                        msg.Recycle();
                    }

                    Thread.Sleep(10);
                    for (int i = 0; i < TestData.Length; ++i)
                    {
                        Assert.AreEqual(TestData[i], output.ReadByte());
                    }
                }
        }
        public void KeepAliveServerTest()
        {
            ManualResetEvent mutex = new ManualResetEvent(false);

            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    UdpConnection client = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        client = (UdpConnection)args.Connection;
                        client.KeepAliveInterval = 100;

                        Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.AreEqual(ConnectionState.Connected, client.State);

                    Assert.IsTrue(
                        client.Statistics.TotalBytesSent >= 27 &&
                        client.Statistics.TotalBytesSent <= 50,
                        "Sent: " + client.Statistics.TotalBytesSent
                        );
                }
        }
Esempio n. 3
0
        public void KeepAliveServerTest()
        {
            ManualResetEvent mutex = new ManualResetEvent(false);

            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.NewConnection += delegate(object sender, NewConnectionEventArgs args)
                    {
                        ((UdpConnection)args.Connection).KeepAliveInterval = 100;

                        Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                        Assert.IsTrue(
                            args.Connection.Statistics.TotalBytesSent >= 30 &&
                            args.Connection.Statistics.TotalBytesSent <= 50,
                            "Sent: " + args.Connection.Statistics.TotalBytesSent
                            );

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();
                }
        }
        public void ServerExtraDataDisconnectTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    MessageReader    received = null;
                    ManualResetEvent mutex    = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        received = args.Message;
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        MessageWriter writer = MessageWriter.Get(SendOption.None);
                        writer.Write("Goodbye");
                        args.Connection.Disconnect("Testing", writer);
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.IsNotNull(received);
                    Assert.AreEqual("Goodbye", received.ReadString());
                }
        }
        public void PingDisconnectClientTest()
        {
#if DEBUG
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();

                    // After connecting, quietly stop responding to all messages to fake connection loss.
                    Thread.Sleep(10);
                    listener.TestDropRate = 1;

                    connection.KeepAliveInterval = 100;

                    Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.AreEqual(ConnectionState.NotConnected, connection.State);
                    Assert.AreEqual(3 * connection.MissingPingsUntilDisconnect + 4, connection.Statistics.TotalBytesSent); // + 4 for connecting overhead
                }
#else
            Assert.Inconclusive("Only works in DEBUG");
#endif
        }
        public void FalseConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int connects = 0;
                    listener.NewConnection += (obj) =>
                    {
                        Interlocked.Increment(ref connects);
                        obj.HandshakeData.Recycle();
                    };

                    listener.Start();

                    socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    var bytes = new byte[2];
                    bytes[0] = (byte)32;
                    for (int i = 0; i < 10; ++i)
                    {
                        socket.SendTo(bytes, new IPEndPoint(IPAddress.Loopback, 4296));
                    }

                    Thread.Sleep(500);

                    Assert.AreEqual(0, connects);
                }
        }
Esempio n. 7
0
        public void UdpHandshakeTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };

            using (ManualResetEventSlim mutex = new ManualResetEventSlim(false))
                using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                    using (UdpConnection connection = new UnityUdpClientConnection(logger, new IPEndPoint(IPAddress.Loopback, 4296)))
                    {
                        listener.Start();

                        MessageReader output = null;
                        listener.NewConnection += delegate(NewConnectionEventArgs e)
                        {
                            output = e.HandshakeData.Duplicate();
                            mutex.Set();
                        };

                        connection.Connect(TestData);
                        mutex.Wait(5000);

                        for (int i = 0; i < TestData.Length; ++i)
                        {
                            Assert.AreEqual(TestData[i], output.ReadByte());
                        }
                    }
        }
        public void ServerDisposeDisconnectsTest()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);

            bool serverConnected    = false;
            bool serverDisconnected = false;
            bool clientDisconnected = false;

            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(ep))
                {
                    listener.NewConnection += (evt) =>
                    {
                        serverConnected              = true;
                        evt.Connection.Disconnected += (o, et) => serverDisconnected = true;
                    };
                    connection.Disconnected += (o, evt) => clientDisconnected = true;

                    listener.Start();
                    connection.Connect();

                    Thread.Sleep(100); // Gotta wait for the server to set up the events.
                    listener.Dispose();
                    Thread.Sleep(100);

                    Assert.IsTrue(serverConnected);
                    Assert.IsTrue(clientDisconnected);
                    Assert.IsFalse(serverDisconnected);
                }
        }
Esempio n. 9
0
        /// <summary>
        /// Start this instance.
        /// </summary>
        public void Start()
        {
            //https://stackoverflow.com/questions/2586612/how-to-keep-a-net-console-app-running
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                _quitEvent.Set();
                eArgs.Cancel = true;
            };

            //Connect and create users collection for LiteDB.org
            //Get users collection
            var col = db.GetCollection <Users>("users");

            if (col.Count() == 0)
            {
                ScryptEncoder encoder         = new ScryptEncoder();
                string        hashsedPassword = encoder.Encode("test1234!");
                //Console.WriteLine(hashsedPassword);
                //Same password
                //string hashsedPassword2 = encoder.Encode("test1234!");
                //Console.WriteLine(hashsedPassword);
                // Create your new customer instance
                var user = new Users
                {
                    UserName     = "******",
                    UserPassword = hashsedPassword,
                    IsActive     = true
                };

                // Create unique index in Name field
                col.EnsureIndex(x => x.UserName, true);

                // Insert new customer document (Id will be auto-incremented)
                col.Insert(user);
            }

            NetworkEndPoint    endPoint = new NetworkEndPoint(IPAddress.Any, portNumber);
            ConnectionListener listener = new UdpConnectionListener(endPoint);

            Running = true;

            Console.WriteLine("Starting server!");
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
            string version = fvi.FileVersion;

            Console.WriteLine("Server Version: " + version);
            Console.WriteLine("BD file path: " + Path.Combine(AssemblyDirectory, @"UsersObjects.db"));
            Console.WriteLine("Server listening on " + (listener as UdpConnectionListener).EndPoint);
            listener.NewConnection += NewConnectionHandler;
            listener.Start();

            _quitEvent.WaitOne();

            //Close all
            listener.Close();
            //Exit 0
            Environment.Exit(0);
        }
 /// <summary>
 ///     Test that a disconnect is sent when the client is disposed.
 /// </summary>
 public void ClientDisconnectOnDisposeTest()
 {
     using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
         using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
         {
             TestHelper.RunClientDisconnectOnDisposeTest(listener, connection);
         }
 }
 public void UdpReliableClientToServerTest()
 {
     using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
         using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
         {
             TestHelper.RunClientToServerTest(listener, connection, 10, SendOption.Reliable);
         }
 }
 public void ServerDisconnectTest()
 {
     using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
         using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
         {
             TestHelper.RunServerDisconnectTest(listener, connection);
         }
 }
 public void UdpFragmentedClientToServerTest()
 {
     using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
         using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
         {
             TestHelper.RunClientToServerTest(listener, connection, (int)(connection.FragmentSize * 9.5), SendOption.FragmentedReliable);
         }
 }
 public void UdpUnreliableServerToClientTest()
 {
     using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
         using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
         {
             TestHelper.RunServerToClientTest(listener, connection, 10, SendOption.None);
         }
 }
Esempio n. 15
0
        public void UdpIPv4ConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(logger, new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                }
        }
        public void UdpIPv4ConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296, IPMode.IPv4)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    listener.Start();

                    connection.Connect();
                }
        }
Esempio n. 17
0
        static void Main(string[] args)
        {
            listener = new UdpConnectionListener(host, 1230);
            listener.Start();

            CancellationTokenSource source = new CancellationTokenSource();

            Console.WriteLine("Server");
            _ = Task.Run(AcceptLoop);
            string msg = Console.ReadLine();
        }
Esempio n. 18
0
        public Matchmaker(IPAddress ip, int port)
        {
            _gameManager   = new GameManager();
            _clientManager = new ClientManager();
            _connection    = new UdpConnectionListener(new IPEndPoint(ip, port), IPMode.IPv4, s =>
            {
                Logger.Warning("Log from Hazel: {0}", s);
            });

            _connection.NewConnection += OnNewConnection;
        }
        public void UdpIPv6ConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.IPv6Any, 4296), IPMode.IPv6))
            {
                listener.Start();

                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), IPMode.IPv6))
                {
                    connection.Connect();
                }
            }
        }
Esempio n. 20
0
        public async ValueTask StartAsync(IPEndPoint ipEndPoint)
        {
            var mode = ipEndPoint.AddressFamily switch
            {
                AddressFamily.InterNetwork => IPMode.IPv4,
                AddressFamily.InterNetworkV6 => IPMode.IPv6,
                _ => throw new InvalidOperationException()
            };

            _connection = new UdpConnectionListener(ipEndPoint, _readerPool, mode);
            _connection.NewConnection = OnNewConnection;

            await _connection.StartAsync();
        }
Esempio n. 21
0
        public Matchmaker(
            ILogger <Matchmaker> logger,
            IOptions <ServerConfig> serverConfig,
            IClientManager clientManager)
        {
            _logger        = logger;
            _serverConfig  = serverConfig.Value;
            _clientManager = clientManager;
            _connection    = new UdpConnectionListener(new IPEndPoint(IPAddress.Parse(_serverConfig.ListenIp), _serverConfig.ListenPort), IPMode.IPv4, s =>
            {
                _logger.LogWarning("Log from Hazel: {0}", s);
            });

            _connection.NewConnection += OnNewConnection;
        }
        public void UdpHandshakeTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296, IPMode.IPv4)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    listener.Start();

                    listener.NewConnection += delegate(object sender, NewConnectionEventArgs e)
                    {
                        Assert.IsTrue(Enumerable.SequenceEqual(e.HandshakeData, new byte[] { 1, 2, 3, 4, 5, 6 }));
                    };

                    connection.Connect(new byte[] { 1, 2, 3, 4, 5, 6 });
                }
        }
Esempio n. 23
0
        public void TcpDualModeConnectionTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(IPAddress.Any, 4296, IPMode.IPv4AndIPv6))
            {
                listener.Start();

                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4)))
                {
                    connection.Connect();
                }

                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296, IPMode.IPv4AndIPv6)))
                {
                    connection.Connect();
                }
            }
        }
Esempio n. 24
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var endpoint = new IPEndPoint(IPAddress.Parse(_config.ResolveListenIp()), _config.ListenPort);

            var mode = endpoint.AddressFamily switch
            {
                AddressFamily.InterNetwork => IPMode.IPv4,
                AddressFamily.InterNetworkV6 => IPMode.IPv6,
                _ => throw new InvalidOperationException()
            };

            _connection = new UdpConnectionListener(endpoint, _readerPool, mode)
            {
                NewConnection = OnNewConnection,
            };

            await _connection.StartAsync();
        }
        public void KeepAliveClientTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new NetworkEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                    connection.KeepAliveInterval = 100;

                    System.Threading.Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.IsTrue(
                        connection.Statistics.TotalBytesSent >= 30 &&
                        connection.Statistics.TotalBytesSent <= 50,
                        "Sent: " + connection.Statistics.TotalBytesSent
                        );
                }
        }
Esempio n. 26
0
        public void KeepAliveClientTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UnityUdpClientConnection(logger, new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                    connection.KeepAliveInterval = 100;

                    Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                    Assert.IsTrue(
                        connection.Statistics.TotalBytesSent >= 30 &&
                        connection.Statistics.TotalBytesSent <= 50,
                        "Sent: " + connection.Statistics.TotalBytesSent
                        );
                }
        }
        public void UdpFieldTest()
        {
            NetworkEndPoint ep = new NetworkEndPoint(IPAddress.Loopback, 4296);

            using (UdpConnectionListener listener = new UdpConnectionListener(new NetworkEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(ep))
                {
                    listener.Start();

                    connection.Connect();

                    //Connection fields
                    Assert.AreEqual(ep, connection.EndPoint);

                    //UdpConnection fields
                    Assert.AreEqual(new IPEndPoint(IPAddress.Loopback, 4296), connection.RemoteEndPoint);
                    Assert.AreEqual(1, connection.Statistics.DataBytesSent);
                    Assert.AreEqual(0, connection.Statistics.DataBytesReceived);
                }
        }
    static void Main(string[] args)
    {
        //Setup listener
        using (UdpConnectionListener listener = new UdpConnectionListener(IPAddress.Any, 4296))
        {
            //Start listening for new connection events
            listener.NewConnection += delegate(object sender, NewConnectionEventArgs a)
            {
                //Send the client some data
                a.Connection.SendBytes(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, SendOption.Reliable);

                //Disconnect from the client
                a.Connection.Close();
            };

            listener.Start();

            Console.ReadKey();
        }
    }
Esempio n. 29
0
        /// <summary>
        /// Start this instance.
        /// </summary>
        public void Start()
        {
            NetworkEndPoint    endPoint = new NetworkEndPoint(IPAddress.Any, portNumber);
            ConnectionListener listener = new UdpConnectionListener(endPoint);

            Running = true;

            Console.WriteLine("Starting server!");
            Console.WriteLine("Server listening on " + (listener as UdpConnectionListener).EndPoint);
            listener.NewConnection += NewConnectionHandler;
            listener.Start();

            while (Running)
            {
                //Do nothing
            }

            //Close all
            listener.Close();
            //Exit 0
            Environment.Exit(0);
        }
        public void ServerExtraDataDisconnectTest()
        {
            using (UdpConnectionListener listener = new UdpConnectionListener(new IPEndPoint(IPAddress.Any, 4296)))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    string           received = null;
                    ManualResetEvent mutex    = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        // We don't own the message, we have to read the string now
                        received = args.Message.ReadString();
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        // As it turns out, the UdpConnectionListener can have an issue on loopback where the disconnect can happen before the hello confirm
                        // Tossing it on a different thread makes this test more reliable. Perhaps something to think about elsewhere though.
                        Task.Run(async() =>
                        {
                            await Task.Delay(1);
                            MessageWriter writer = MessageWriter.Get(SendOption.None);
                            writer.Write("Goodbye");
                            args.Connection.Disconnect("Testing", writer);
                        });
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.IsNotNull(received);
                    Assert.AreEqual("Goodbye", received);
                }
        }