Пример #1
0
        public async Task SocketTimeout3()
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            try
            {
                var endpoint = NetworkAddress.Parse("127.0.0.1:11000").IPEndPoint;
                await socket.ConnectAsync(endpoint, 60_000).CfAwait();

                Assert.Fail("Expected an exception.");
            }
            catch (TimeoutException)
            {
                Assert.Fail("Did not expect TimeoutException.");
            }
            catch (Exception)
            {
                // ok
            }

            // socket is not ready (but not disposed)
            Assert.Throws <SocketException>(() =>
            {
                socket.Send(Array.Empty <byte>());
            });
        }
Пример #2
0
        static async Task Main(string[] args)
        {
            //Get configuration
            var networkAddress = NetworkAddress.Parse(ConfigurationManager.AppSettings["Network"]);
            var broadcastPort  = int.Parse(ConfigurationManager.AppSettings["BroadcastUdpPort"]);
            var unicastPort    = int.Parse(ConfigurationManager.AppSettings["UnicastTcpPort"]);

            localAddress = networkAddress.GetLocalAddress();

            //This client exposes all of the high-level functionality
            var collaborationClient = new CollaborationClient(networkAddress, broadcastPort, unicastPort);

            collaborationClient.CollaborationRequestAccepted          += OnCollaborationRequestAccepted;
            collaborationClient.CollaborationRequestDeclined          += OnCollaborationRequestDeclined;
            collaborationClient.StopCollaborationRequested            += OnStopCollaborationRequested;
            collaborationClient.SubscriptionRequested                 += OnSubscriptionRequested;
            collaborationClient.SubscriberNotifiedToStopCollaborating += OnSubscriberNotifiedToStopCollaborating;

            //Start listening per collaboration requests broadcasts
            var broadcastListenTask = StartListeningForCollaborationRequests(collaborationClient, listeningCancellationTokenSource.Token);
            //And also listen for subscription requests
            var subscriptionListenTask = StartListeningForSubscriptions(collaborationClient, listeningCancellationTokenSource.Token);

            //Then, read commands from the user
            HandleUserInput(collaborationClient);

            //When it's time to close the app, cancel any pending work and shutdown the hosts
            workCancellationTokenSource?.Cancel();
            await Task.WhenAll(broadcastListenTask, subscriptionListenTask);
        }
Пример #3
0
        public void ShouldTriggerPeersDataWhenLocal()
        {
            NetworkAddress remote = NetworkAddress.Parse(IPAddress.Loopback, 8345);

            using (PeersFixture fixture = new PeersFixture())
                using (PeersSession session = fixture.Start())
                {
                    NetworkConnection connection = A.Fake <NetworkConnection>();
                    Handshake         handshake  = new Handshake(PeerHash.Random(), PeerHash.Random(), session.Coordinator.Hash, HandshakeOptions.Extended);

                    MessageReceived extended = new MessageReceived
                    {
                        Type    = "extended",
                        Peer    = handshake.Remote,
                        Payload = new PeersMessage("d1:md6:ut_pexi3eee")
                    };

                    Trigger handler = Trigger.Bind(ref session.Plugin.Hooks.OnPeersDataSent, data =>
                    {
                        data.Peer.Should().Be(handshake.Remote);
                        data.Hash.Should().Be(session.Coordinator.Hash);
                        data.Remotes.Should().Contain(remote);
                    });

                    session.Coordinator.Start();
                    session.Coordinator.Connect(connection, handshake);

                    session.Coordinator.Handle(extended);
                    session.Coordinator.SendPeers(handshake.Remote, remote);

                    handler.Wait().Should().BeTrue();
                }
        }
Пример #4
0
        public async Task ShouldTriggerConnectionSentWhenSentSomeBytes()
        {
            NetworkDirection       direction = NetworkDirection.Outgoing;
            NetworkOutgoingMessage message   = new RandomMessage(113);

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);
                        host.Accept(null);

                        await socket.Connect(endpoint);

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        Trigger           handler    = Trigger.Bind(ref fixture.Hooks.OnConnectionSent, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().Be(connection);
                            data.Bytes.Should().Be(message.Length);
                        });

                        connection.Send(message);
                        handler.Wait().Should().BeTrue();
                    }
        }
Пример #5
0
        public void MemberInfoTest()
        {
            var memberId = Guid.NewGuid();
            var address  = NetworkAddress.Parse("192.168.33.34:5569");
            var version  = new MemberVersion(4, 5, 6);


            var attributes = new Dictionary <string, string>
            {
                { "attribute", "value" }
            };
            var x = new MemberInfo(memberId, address, version, true, attributes);

            Console.WriteLine(x);

            Assert.That(x.Id, Is.EqualTo(memberId));
            Assert.That(x.Uuid, Is.EqualTo(memberId));
            Assert.That(x.Address, Is.SameAs(address));
            Assert.That(x.Version, Is.SameAs(version));
            Assert.That(x.IsLite, Is.True);
            Assert.That(x.IsLiteMember, Is.True);
            var a = x.Attributes;

            Assert.That(a.Count, Is.EqualTo(1));
            Assert.That(a["attribute"], Is.EqualTo("value"));

            Assert.That(x, Resolves.Equatable(
                            // weird indeed, but only the ID matters
                            new MemberInfo(memberId, x.Address, x.Version, x.IsLite, attributes),
                            new MemberInfo(Guid.NewGuid(), x.Address, x.Version, x.IsLite, attributes)
                            ));
        }
Пример #6
0
        private void OnAccept(TcpSocketAccept data)
        {
            bool canAcceptMore =
                data.Status != SocketStatus.NotSocket &&
                data.Status != SocketStatus.OperationAborted;

            if (canAcceptMore)
            {
                data.Socket.Accept(OnAccept);
            }

            if (data.Status == SocketStatus.OK)
            {
                IPEndPoint     endpoint = data.GetRemote();
                NetworkAddress remote   = NetworkAddress.Parse(endpoint);

                NetworkDirection  direction  = NetworkDirection.Incoming;
                NetworkConnection connection = dependencies.Network.Create(data.Connection, direction, endpoint);

                hooks.CallConnectionArrived(remote, connection);
            }
            else
            {
                data.Connection?.Dispose();
            }
        }
        public void ArgumentExceptions()
        {
            var endpoint = NetworkAddress.Parse("127.0.0.1:11000").IPEndPoint;
            var s        = new ClientSocketConnection(1, endpoint, new NetworkingOptions(), new SslOptions(), new NullLoggerFactory());
            var c        = new ClientMessageConnection(s, new NullLoggerFactory());

            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await c.SendAsync(null));
        }
Пример #8
0
        public async Task TimeoutsAfterMultipleRetries()
        {
            var address = NetworkAddress.Parse("127.0.0.1:11001");

            using var _ = HConsole.Capture(consoleOptions => consoleOptions
                                           .ClearAll()
                                           .Configure().SetMaxLevel()
                                           .Configure(this).SetPrefix("TEST")
                                           .Configure <AsyncContext>().SetMinLevel()
                                           .Configure <SocketConnectionBase>().SetIndent(1).SetLevel(0).SetPrefix("SOCKET"));

            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start server");
            await using var server = new Server(address, async(xsvr, xconn, xmsg)
                                                => await HandleAsync(xsvr, xconn, xmsg, async(svr, conn, msg) =>
            {
                HConsole.WriteLine(svr, "Handle request (wait...)");
                await Task.Delay(500).CfAwait();

                HConsole.WriteLine(svr, "Respond with error.");
                var response = ErrorsServerCodec.EncodeResponse(new[]
                {
                    // make sure the error is retryable
                    new ErrorHolder(RemoteError.RetryableHazelcast, "classname", "message", Enumerable.Empty <StackTraceElement>())
                });

                //HConsole.WriteLine(svr, "Respond with success.");
                //var response = ClientPingServerCodec.EncodeResponse();

                response.CorrelationId = msg.CorrelationId;
                await conn.SendAsync(response).CfAwait();
            }), LoggerFactory);
            await server.StartAsync().CfAwait();

            HConsole.WriteLine(this, "Start client");
            var options = HazelcastOptions.Build(configure: (configuration, options) =>
            {
                options.Networking.Addresses.Add("127.0.0.1:11001");
                options.Messaging.RetryTimeoutSeconds = 3; // default value is 120s
            });

            await using var client = (HazelcastClient) await HazelcastClientFactory.StartNewClientAsync(options);

            HConsole.WriteLine(this, "Send message");
            var message = ClientPingServerCodec.EncodeRequest();

            // note: the error only happens *after* the server has responded
            // we could wait for the response for ever
            await AssertEx.ThrowsAsync <TaskTimeoutException>(async() =>
            {
                // server will respond w/ error every 500ms and client will retry
                // until the 3s retry timeout (options above) is reached
                await client.Cluster.Messaging.SendAsync(message).CfAwait();
            });

            await server.StopAsync().CfAwait();
        }
        public async Task Test()
        {
            //var host = Dns.GetHostEntry(_hostname);
            //var ipAddress = host.AddressList[0];
            //var endpoint = new IPEndPoint(ipAddress, _port);

            var address = NetworkAddress.Parse("127.0.0.1:11001");

            HConsole.Configure(this, config => config.SetIndent(0).SetPrefix("TEST"));
            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start server");
            var server = new Server(address, ReceiveMessage, LoggerFactory);
            await server.StartAsync().CAF();

            var options = HazelcastOptions.Build(Array.Empty <string>(), configure: (configuration, options) =>
            {
                options.Networking.Addresses.Add("127.0.0.1:11001");
            });

            HConsole.WriteLine(this, "Start client 1");
            await using var client1 = (HazelcastClient)HazelcastClientFactory.CreateClient(options);
            await client1.StartAsync().CAF();

            HConsole.WriteLine(this, "Send message 1 to client 1");
            var message  = CreateMessage("ping");
            var response = await client1.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            HConsole.WriteLine(this, "Start client 2");
            await using var client2 = (HazelcastClient)HazelcastClientFactory.CreateClient(options);
            await client2.StartAsync().CAF();

            HConsole.WriteLine(this, "Send message 1 to client 2");
            message  = CreateMessage("a");
            response = await client2.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            HConsole.WriteLine(this, "Send message 2 to client 1");
            message  = CreateMessage("foo");
            response = await client1.Cluster.Messaging.SendAsync(message, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Got response: " + GetText(response));

            //XConsole.WriteLine(this, "Stop client");
            //await client1.CloseAsync().CAF();

            HConsole.WriteLine(this, "Stop server");
            await server.StopAsync().CAF();

            await Task.Delay(1000).CAF();

            HConsole.WriteLine(this, "End");
            await Task.Delay(100).CAF();
        }
Пример #10
0
        public async Task Exceptions()
        {
            var endpoint = NetworkAddress.Parse("127.0.0.1:5701").IPEndPoint;
            var options  = new SocketOptions();

            await using var connection = new ClientSocketConnection(0, endpoint, options, new SslOptions(), new NullLoggerFactory(), 3);

            // OnReceiveMessageBytes is missing
            Assert.ThrowsAsync <InvalidOperationException>(async() => await connection.ConnectAsync(default));
Пример #11
0
        public Task InitializeAsync(IDnsServer dnsServer, string config)
        {
            dynamic jsonConfig = JsonConvert.DeserializeObject(config);

            _enableBlocking = jsonConfig.enableBlocking.Value;

            if (jsonConfig.allowedNetworks is null)
            {
                _allowedNetworks = Array.Empty <NetworkAddress>();
            }
            else
            {
                List <NetworkAddress> allowedNetworks = new List <NetworkAddress>();

                foreach (dynamic allowedNetwork in jsonConfig.allowedNetworks)
                {
                    allowedNetworks.Add(NetworkAddress.Parse(allowedNetwork.Value));
                }

                _allowedNetworks = allowedNetworks;
            }

            if (jsonConfig.blockedNetworks is null)
            {
                _blockedNetworks = Array.Empty <NetworkAddress>();
            }
            else
            {
                List <NetworkAddress> blockedNetworks = new List <NetworkAddress>();

                foreach (dynamic blockedNetwork in jsonConfig.blockedNetworks)
                {
                    blockedNetworks.Add(NetworkAddress.Parse(blockedNetwork.Value));
                }

                _blockedNetworks = blockedNetworks;
            }

            if (jsonConfig.blockedQuestions is null)
            {
                _blockedQuestions = Array.Empty <BlockedQuestion>();
            }
            else
            {
                List <BlockedQuestion> blockedQuestions = new List <BlockedQuestion>();

                foreach (dynamic blockedQuestion in jsonConfig.blockedQuestions)
                {
                    blockedQuestions.Add(new BlockedQuestion(blockedQuestion));
                }

                _blockedQuestions = blockedQuestions;
            }

            return(Task.CompletedTask);
        }
        public void Parse()
        {
            Assert.Throws <FormatException>(() => _ = NetworkAddress.Parse("[::1]:uh"));

            var address = NetworkAddress.Parse("127.0.0.1:5701");

            Assert.That(address.HostName, Is.EqualTo("127.0.0.1"));
            Assert.That(address.Port, Is.EqualTo(5701));

            Assert.That(NetworkAddress.TryParse("712.548", out var _), Is.False);

            var addresses = GetAddresses("127.0.0.1");

            Console.WriteLine("127.0.0.1");
            AssertAddresses(addresses, "127.0.0.1", false);

            addresses = GetAddresses("localhost");
            Console.WriteLine("localhost");
            AssertAddresses(addresses, "127.0.0.1", false);

            // on Windows, this gets 127.0.0.1 but on Linux it gets what the host name
            // maps to in /etc/hosts and by default on some systems (eg Debian) it can
            // be 127.0.1.1 instead of 127.0.0.1
            //
            addresses = GetAddresses(Dns.GetHostName());
            Console.Write(Dns.GetHostName());
            var n = Dns.GetHostAddresses(Dns.GetHostName()).First(x => x.AddressFamily == AddressFamily.InterNetwork).ToString();

            Console.WriteLine(" -> " + n);
            AssertAddresses(addresses, n, false);

            addresses = GetAddresses("::1");
            Console.WriteLine("::1");
            AssertAddresses(addresses, "[::1]", true);

            // on Windows, this gets the various fe80 local addresses (but not the random one
            // that we specified) - on Linux this gets nothing and it may eventually be an issue?
            // there are various issues corresponding to this situation,
            // see https://github.com/dotnet/runtime/issues/27534
            // and fixes seem to be in the 5.0 milestone = n/a yet.

            addresses = GetAddresses("fe80::bd0f:a8bc:6480:238b");
            Console.WriteLine("fe80::bd0f:a8bc:6480:238b");
            if (OS.IsWindows)
            {
                // test the first 3, we might get more depending on NICs
                AssertAddresses(addresses, "*", true);
            }
            else
            {
                foreach (var a in addresses)
                {
                    Console.WriteLine("  " + a);
                }
            }
        }
Пример #13
0
        public void PartitionLostEventArgs()
        {
            var memberInfo = new MemberInfo(Guid.NewGuid(), NetworkAddress.Parse("127.0.0.1:88"), new MemberVersion(1, 1, 1), false, new Dictionary <string, string>());
            var args       = new PartitionLostEventArgs(12, 13, true, memberInfo);

            Assert.That(args.PartitionId, Is.EqualTo(12));
            Assert.That(args.LostBackupCount, Is.EqualTo(13));
            Assert.That(args.IsAllReplicasInPartitionLost);
            Assert.That(args.Member, Is.SameAs(memberInfo));
        }
Пример #14
0
        public void Parse()
        {
            Assert.Throws <FormatException>(() => _ = NetworkAddress.Parse("[::1]:uh"));

            var address = NetworkAddress.Parse("127.0.0.1:5701");

            Assert.That(address.HostName, Is.EqualTo("127.0.0.1"));
            Assert.That(address.Port, Is.EqualTo(5701));

            Assert.That(NetworkAddress.TryParse("712.548", out IEnumerable <NetworkAddress> _), Is.False);
        public async Task OnReceiveMessage()
        {
            var endpoint = NetworkAddress.Parse("127.0.0.1:11000").IPEndPoint;
            var s        = new ClientSocketConnection(1, endpoint, new NetworkingOptions(), new SslOptions(), new NullLoggerFactory());
            var c        = new ClientMessageConnection(s, new NullLoggerFactory())
            {
                OnReceiveMessage = OnReceiveMessageNotImplemented
            };

            Assert.That(c.OnReceiveMessage, Is.Not.Null);
            Assert.Throws <NotImplementedException>(() => c.OnReceiveMessage(default, default));
Пример #16
0
        public void ShouldSanitizeNetworkAddress()
        {
            //Arrange
            var stringRepresentation = "192.168.191.128/19";
            var expectedAddress      = IPAddress.Parse("192.168.160.0");

            //Act
            var actualAddress = NetworkAddress.Parse(stringRepresentation).Address;

            //Assert
            Assert.AreEqual(expectedAddress, actualAddress);
        }
        public void Equality()
        {
            var address1 = NetworkAddress.Parse("127.0.0.1:5701");
            var address2 = NetworkAddress.Parse("127.0.0.1:5702");
            var address3 = NetworkAddress.Parse("127.0.0.1:5701");

            Assert.That(address1 == address2, Is.False);
            Assert.That(address1 != address2, Is.True);

            Assert.That(address1 == address3, Is.True);
            Assert.That(address1 != address3, Is.False);
        }
Пример #18
0
        public void ShouldCalculateBroadcastAddress()
        {
            //Arrange
            var stringRepresentation = "192.168.160.0/19";
            var expectedAddress      = IPAddress.Parse("192.168.191.255");

            //Act
            var actualAddress = NetworkAddress.Parse(stringRepresentation).BroadcastAddress;

            //Assert
            Assert.AreEqual(expectedAddress, actualAddress);
        }
        public void ConnectAsyncTimeout2()
        {
            var endpoint = NetworkAddress.Parse("www.hazelcast.com:5701").IPEndPoint;

            using var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            Assert.ThrowsAsync <TimeoutException>(async() =>
            {
                // no time for connection to be refused, timeout exception
                await socket.ConnectAsync(endpoint, 1, CancellationToken.None);
            });
        }
Пример #20
0
        /// <summary>
        /// Creates a new instance of the network connection relying on the
        /// already connected socket instance and direction value indicating
        /// who is the initiator of the connection.
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="socket">The already connected socket.</param>
        /// <param name="direction">The direction indicating who initiated the connection.</param>
        /// <param name="identifier"></param>
        public NetworkPoolConnection(NetworkPoolListener listener, TcpSocket socket, NetworkDirection direction, long identifier, IPEndPoint remote)
        {
            this.listener   = listener;
            this.socket     = socket;
            this.direction  = direction;
            this.identifier = identifier;

            this.remote = NetworkAddress.Parse(remote);

            incoming = new NetworkIncomingBuffer(listener, socket, identifier);
            outgoing = new NetworkOutgoingBuffer(listener, socket, identifier);
        }
Пример #21
0
        public async Task SocketTimeout1()
        {
            await using var server = new Server(NetworkAddress.Parse("127.0.0.1:11000"), (svr, connection, message) => new ValueTask(), LoggerFactory);
            await server.StartAsync().CfAwait();

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            // server is listening, can connect within 1s timeout
            await socket.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000), 1_000).CfAwait();

            socket.Close();
            await server.StopAsync().CfAwait();
        }
Пример #22
0
        public void ShouldParseStringRepresentation()
        {
            //Arrange
            var stringRepresentation    = "192.168.1.0/24";
            var expectedAddress         = IPAddress.Parse("192.168.1.0");
            var expectedSignificantBits = 24;

            //Act
            var networdAddress = NetworkAddress.Parse(stringRepresentation);

            //Assert
            Assert.AreEqual(expectedAddress, networdAddress.Address);
            Assert.AreEqual(expectedSignificantBits, networdAddress.SignificantBits);
        }
Пример #23
0
        public async Task CanRetryAndSucceed()
        {
            var address = NetworkAddress.Parse("127.0.0.1:11001");

            HConsole.Configure(x => x.Configure(this).SetIndent(0).SetPrefix("TEST"));
            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start server");
            var count = 0;

            await using var server = new Server(address, async(xsvr, xconn, xmsg)
                                                => await HandleAsync(xsvr, xconn, xmsg, async(svr, conn, msg) =>
            {
                HConsole.WriteLine(svr, "Handle request.");
                ClientMessage response;
                if (++count > 3)
                {
                    HConsole.WriteLine(svr, "Respond with success.");
                    response = ClientPingServerCodec.EncodeResponse();
                }
                else
                {
                    HConsole.WriteLine(svr, "Respond with error.");
                    response        = CreateErrorMessage(RemoteError.RetryableHazelcast);
                    response.Flags |= ClientMessageFlags.BeginFragment | ClientMessageFlags.EndFragment;
                }
                response.CorrelationId = msg.CorrelationId;
                await conn.SendAsync(response).CfAwait();
            }), LoggerFactory);
            await server.StartAsync().CfAwait();

            HConsole.WriteLine(this, "Start client");
            var options = HazelcastOptions.Build(configure: (configuration, options) =>
            {
                options.Networking.Addresses.Add("127.0.0.1:11001");
            });

            await using var client = (HazelcastClient) await HazelcastClientFactory.StartNewClientAsync(options);

            HConsole.WriteLine(this, "Send message");
            var message = ClientPingServerCodec.EncodeRequest();

            var token = new CancellationTokenSource(3_000).Token;
            await client.Cluster.Messaging.SendAsync(message, token); // default is 120s

            Assert.AreEqual(4, count);

            await server.StopAsync().CfAwait();
        }
Пример #24
0
        public void AuthenticationResultTest()
        {
            var clusterId = Guid.NewGuid();
            var memberId  = Guid.NewGuid();
            var address   = NetworkAddress.Parse("192.168.33.34:5569");

            var x = new AuthenticationResult(clusterId, memberId, address, "4.5.6", true, 12, 4);

            Assert.That(x.ClusterId, Is.EqualTo(clusterId));
            Assert.That(x.MemberId, Is.EqualTo(memberId));
            Assert.That(x.MemberAddress, Is.SameAs(address));
            Assert.That(x.ServerVersion, Is.EqualTo("4.5.6"));
            Assert.That(x.FailoverSupported);
            Assert.That(x.PartitionCount, Is.EqualTo(12));
            Assert.That(x.SerializationVersion, Is.EqualTo(4));
        }
Пример #25
0
        public void bansAfterEnoughFailures()
        {
            for (int i = 0; i < MAX_ALLOWED_FAILURES + 1; i++)
            {
                eventLogListener.failure += Raise.With(null, SOURCE_ADDRESS);
            }

            Assert.NotEmpty(firewallRules);
            FirewallWASRule actual = firewallRules.First();

            Assert.True(actual.IsEnable);
            Assert.Equal("Banned 192.0.2.0/24", actual.Name);
            Assert.Equal("Fail2Ban4Win", actual.Grouping);
            Assert.Equal(FirewallAction.Block, actual.Action);
            Assert.Equal(FirewallDirection.Inbound, actual.Direction);
            Assert.Equal(NetworkAddress.Parse("192.0.2.0/24"), actual.RemoteAddresses[0]);
        }
Пример #26
0
        public void ShouldCreateNewConnection()
        {
            IPAddress        address   = IPAddress.Parse("127.0.0.1");
            IPEndPoint       remote    = new IPEndPoint(address, 8080);
            NetworkDirection direction = NetworkDirection.Outgoing;

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket socket = fixture.Pool.New())
                {
                    NetworkConnection connection = fixture.Pool.Create(socket, direction, remote);

                    connection.Should().NotBeNull();
                    connection.Direction.Should().Be(direction);
                    connection.Remote.Should().Be(NetworkAddress.Parse(remote));
                    connection.Identifier.Should().BeGreaterThan(0);
                }
        }
        public async Task Auth()
        {
            // need to start a real server (not the RC thing!)

            //var address = NetworkAddress.Parse("sgay-l4");
            var address = NetworkAddress.Parse("localhost");

            HConsole.Configure(this, config => config.SetIndent(0).SetPrefix("TEST"));
            HConsole.WriteLine(this, "Begin");

            HConsole.WriteLine(this, "Start client ");
            var client1 = new MemberConnection(address, new MessagingOptions(), new SocketOptions(), new SslOptions(), new Int64Sequence(), new NullLoggerFactory());
            await client1.ConnectAsync(CancellationToken.None).CAF();

            // RC assigns a GUID but the default cluster name is 'dev'
            var clusterName          = "dev";
            var username             = (string)null; // null
            var password             = (string)null; // null
            var clientId             = Guid.NewGuid();
            var clientType           = "CSP";        // CSharp
            var serializationVersion = (byte)0x01;
            var clientVersion        = "4.0";
            var clientName           = "hz.client_0";
            var labels         = new HashSet <string>();
            var requestMessage = ClientAuthenticationCodec.EncodeRequest(clusterName, username, password, clientId, clientType, serializationVersion, clientVersion, clientName, labels);

            HConsole.WriteLine(this, "Send auth request");
            var invocation      = new Invocation(requestMessage, new MessagingOptions(), null, CancellationToken.None);
            var responseMessage = await client1.SendAsync(invocation, CancellationToken.None).CAF();

            HConsole.WriteLine(this, "Rcvd auth response " +
                               HConsole.Lines(this, 1, responseMessage.Dump()));
            var response = ClientAuthenticationCodec.DecodeResponse(responseMessage);

            var status = (AuthenticationStatus)response.Status;

            NUnit.Framework.Assert.AreEqual(AuthenticationStatus.Authenticated, status);

            HConsole.WriteLine(this, "Stop client");
            await client1.DisposeAsync().CAF();

            HConsole.WriteLine(this, "End");
            await Task.Delay(100).CAF();
        }
Пример #28
0
        public void ShouldTriggerConnectionRejected()
        {
            using (ConnectorFixture fixture = new ConnectorFixture())
                using (ConnectorSession session = fixture.Start())
                {
                    FileHash       hash    = FileHash.Random();
                    NetworkAddress address = NetworkAddress.Parse(session.Endpoint);

                    Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionEstablished, data =>
                    {
                        data.Remote.Should().NotBeNull();
                        data.Remote.Host.Should().Be("127.0.0.1");
                        data.Remote.Port.Should().Be(session.Endpoint.Port);
                    });

                    session.Connector.ConnectTo(hash, address);
                    handler.Wait().Should().BeTrue();
                }
        }
        public async Task Test()
        {
            using var _ = HConsoleForTest();

            var options = HazelcastOptions.Build();

            options.Messaging.RetryTimeoutSeconds = 1;

            var loggerFactory = new NullLoggerFactory();

            var address = NetworkAddress.Parse("127.0.0.1:11000");

            var state = new ServerState
            {
                Id       = 0,
                MemberId = Guid.NewGuid(),
                Address  = address
            };

            await using var server = new Server(address, ServerHandler, loggerFactory, state, "0")
                        {
                            MemberId = state.MemberId,
                        };
            await server.StartAsync();

            var serializationService = HazelcastClientFactory.CreateSerializationService(options.Serialization, loggerFactory);
            var authenticator        = new Authenticator(options.Authentication, serializationService);

            ISequence <int>  connectionIdSequence  = new Int32Sequence();
            ISequence <long> correlationIdSequence = new Int64Sequence();

            var memberConnection = new MemberConnection(address, authenticator,
                                                        options.Messaging, options.Networking, options.Networking.Ssl,
                                                        connectionIdSequence, correlationIdSequence,
                                                        loggerFactory);

            var memberConnectionHasClosed = false;

            memberConnection.Closed += connection =>
            {
                memberConnectionHasClosed = true;
                return(default);
Пример #30
0
        public async Task ShouldTriggerConnectionReceivedWhenReceivedSomeBytes()
        {
            NetworkDirection       direction = NetworkDirection.Outgoing;
            NetworkOutgoingMessage message   = new RandomMessage(113);

            using (NetworkFixture fixture = new NetworkFixture())
                using (TcpSocket host = fixture.Pool.New())
                    using (TcpSocket socket = fixture.Pool.New())
                    {
                        TcpSocketInfo info     = host.BindAndInfo();
                        int           port     = info.Endpoint.Port;
                        IPEndPoint    endpoint = new IPEndPoint(IPAddress.Loopback, port);

                        socket.Bind();
                        host.Listen(10);

                        Task <TcpSocketAccept> task = host.Accept();
                        await socket.Connect(endpoint);

                        TcpSocketAccept accept = await task;

                        NetworkConnection connection = fixture.Pool.Create(socket, direction, endpoint);
                        NetworkBlock      block      = new NetworkBlock(new byte[1024], 0, message.Length);

                        Trigger handler = Trigger.Bind(ref fixture.Hooks.OnConnectionReceived, data =>
                        {
                            data.Remote.Should().Be(NetworkAddress.Parse(endpoint));
                            data.Connection.Should().NotBeNull();
                            data.Bytes.Should().Be(message.Length);
                        });

                        connection.Receive(new NullReceiver());
                        message.ToBytes(block);

                        block.With((buffer, offset, count) =>
                        {
                            accept.Connection.Send(new SocketBuffer(buffer, offset, count), null);
                        });

                        handler.Wait().Should().BeTrue();
                    }
        }