Пример #1
0
        public void StartAndStopStateValidation()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    // Send a message through to ensure the proxy has started
                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");
                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    Assert.Throws <InvalidOperationException>(proxy.Start);
                    Assert.Throws <InvalidOperationException>(proxy.Start);
                    Assert.Throws <InvalidOperationException>(proxy.Start);

                    proxy.Stop(); // blocks until stopped

                    Assert.Throws <InvalidOperationException>(proxy.Stop);
                }
        }
Пример #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("====== SINK ======");

            using (var sink = new DealerSocket())
            {
                sink.Bind("tcp://127.0.0.1:7777");

                var startOfBatchTrigger = sink.ReceiveFrameString();
                Console.WriteLine("Seen start of batch");

                var watch = new Stopwatch();
                watch.Start();

                for (int taskNumber = 0; taskNumber < 100; taskNumber++)
                {
                    var workerDoneTrigger = sink.ReceiveFrameString();

                    if (taskNumber % 10 == 0)
                    {
                        Console.Write(":");
                    }
                    else
                    {
                        Console.Write(".");
                    }
                }

                watch.Stop();

                Console.WriteLine();
                Console.WriteLine($"Total elapsed time {watch.ElapsedMilliseconds} msec");
                Console.ReadLine();
            }
        }
Пример #3
0
        public void SendAndReceive()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");

                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    proxy.Stop();
                }
        }
Пример #4
0
        public void CurveTest()
        {
            var serverPair = new NetMQCertificate();

            using var server                = new DealerSocket();
            server.Options.CurveServer      = true;
            server.Options.CurveCertificate = serverPair;
            server.Bind($"tcp://127.0.0.1:55367");

            var clientPair = new NetMQCertificate();

            using var client = new DealerSocket();
            client.Options.CurveServerKey   = serverPair.PublicKey;
            client.Options.CurveCertificate = clientPair;
            client.Connect("tcp://127.0.0.1:55367");

            for (int i = 0; i < 100; i++)
            {
                client.SendFrame("Hello");
                var hello = server.ReceiveFrameString();
                Assert.Equal("Hello", hello);

                server.SendFrame("World");
                var world = client.ReceiveFrameString();
                Assert.Equal("World", world);
            }
        }
Пример #5
0
        public void WithLibzmqClient()
        {
            using (var ctx = new ZContext())
                using (var client = ZSocket.Create(ctx, ZSocketType.DEALER))
                    using (var server = new DealerSocket())
                    {
                        var serverPair = new NetMQCertificate();
                        server.Options.CurveServer      = true;
                        server.Options.CurveCertificate = serverPair;
                        server.Bind($"tcp://127.0.0.1:55367");

                        var clientCert = new ZCert();
                        client.CurveSecretKey = clientCert.SecretKey;
                        client.CurvePublicKey = clientCert.PublicKey;
                        client.CurveServerKey = serverPair.PublicKey;
                        client.Connect("tcp://127.0.0.1:55367");

                        client.SendBytes(Encoding.ASCII.GetBytes("Hello"), 0, 5);
                        var hello = server.ReceiveFrameString();
                        Assert.Equal("Hello", hello);

                        server.SendFrame("Hello");
                        var frame = client.ReceiveFrame();
                        Assert.Equal("Hello", frame.ReadString());
                    }
        }
Пример #6
0
        public void ReconnectOnRouterBug()
        {
            {
                using (var dealer = new DealerSocket())
                {
                    dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer");
                    dealer.Bind("tcp://localhost:6667");

                    using (var router = new RouterSocket())
                    {
                        router.Options.RouterMandatory = true;
                        router.Connect("tcp://localhost:6667");
                        Thread.Sleep(100);

                        router.SendMoreFrame("dealer").SendFrame("Hello");
                        var message = dealer.ReceiveFrameString();
                        Assert.That(message == "Hello");

                        router.Disconnect("tcp://localhost:6667");
                        Thread.Sleep(1000);
                        router.Connect("tcp://localhost:6667");
                        Thread.Sleep(100);

                        router.SendMoreFrame("dealer").SendFrame("Hello");
                        message = dealer.ReceiveFrameString();
                        Assert.That(message == "Hello");
                    }
                }
            }
        }
Пример #7
0
 /// <summary>
 /// 绑定本地代理
 /// </summary>
 /// <param name="frontAddress"></param>
 /// <param name="backAddress"></param>
 public void Bind(string frontAddress, string backAddress)
 {
     frontEnd = new RouterSocket();
     backEnd  = new DealerSocket();
     frontEnd.Bind(frontAddress);
     backEnd.Bind(backAddress);
     proxy = new Proxy(frontEnd, backEnd);
     Task.Factory.StartNew(proxy.Start);
 }
Пример #8
0
        public void Start()
        {
            _dealerSocket.Bind(_dealerAddress);
            _publisherSocket.Bind(_publisherAddress);

            _dealerSocket.ReceiveReady += HandleReceiveEvent;

            _poller.Run();
        }
Пример #9
0
 public AsyncBrocker(NetMQContext context, string address)
 {
     _socket = context.CreateDealerSocket();
     _socket.Options.SendHighWatermark = 1;
     _socket.Options.ReceiveHighWatermark = 1;
     _socket.Bind(address);
     _socket.ReceiveReady += SocketReceiveReady;
     _poller.AddSocket(_socket);
     _poller.PollTillCancelledNonBlocking();
 }
Пример #10
0
        public void Do()
        {
            // we are using dealer here, but we can use router as well, we just have to manager
            // SecureChannel for each identity
            using (var socket = new DealerSocket())
            {
                socket.Bind("tcp://*:9696");

                using (SecureChannel secureChannel = SecureChannel.CreateServerSecureChannel(m_configuration))
                {
                    // we need to set X509Certificate with a private key for the server
                    X509Certificate2 certificate = new X509Certificate2(
                        System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.pfx"), "1234");
                    secureChannel.Certificate = certificate;

                    List <NetMQMessage> outgoingMessages = new List <NetMQMessage>();

                    // waiting for message from client
                    NetMQMessage incomingMessage = socket.ReceiveMultipartMessage();
                    //SplitInMessage

                    // calling ProcessMessage until ProcessMessage return true
                    // and the SecureChannel is ready to encrypt and decrypt messages
                    while (!secureChannel.ProcessMessage(incomingMessage, outgoingMessages))
                    {
                        //SendMessages(socket,outgoingMessages);
                        foreach (NetMQMessage message in outgoingMessages)
                        {
                            socket.SendMultipartMessage(message);
                        }
                        outgoingMessages.Clear();
                        incomingMessage = socket.ReceiveMultipartMessage();
                    }
                    //SendMessages(socket, outgoingMessages);
                    foreach (NetMQMessage message in outgoingMessages)
                    {
                        socket.SendMultipartMessage(message);
                    }
                    outgoingMessages.Clear();

                    // this message is now encrypted
                    NetMQMessage cipherMessage = socket.ReceiveMultipartMessage();

                    // decrypting the message
                    NetMQMessage plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage);
                    System.Console.WriteLine(plainMessage.First.ConvertToString());
                    plainMessage = new NetMQMessage();
                    plainMessage.Append("Worldddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");

                    // encrypting the message and sending it over the socket
                    socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage));
                }
            }
        }
Пример #11
0
        private void ProxyThread()
        {
            RouterSocket router = null;
            DealerSocket dealer = null;

            try
            {
                router = _ctx.CreateRouterSocket();
                dealer = _ctx.CreateDealerSocket();
                router.Bind(_frontendAddress);
                switch (_backendCxMode)
                {
                case ConnectionMode.Connect:
                    dealer.Connect(_backendAddress);
                    break;

                case ConnectionMode.Bind:
                    dealer.Bind(_backendAddress);
                    break;
                }

                router.Options.Linger = TimeSpan.Zero;
                dealer.Options.Linger = TimeSpan.Zero;
                var xproxy = new Proxy(router, dealer, null);
                xproxy.Start();
            }
            catch (TerminatingException)
            {
            }
            finally
            {
                if (router != null)
                {
                    try
                    {
                        router.Dispose();
                    }
                    catch (NetMQException)
                    {
                    }
                }
                if (dealer != null)
                {
                    try
                    {
                        dealer.Dispose();
                    }
                    catch (NetMQException)
                    {
                    }
                }
            }
        }
Пример #12
0
        public void Disconnect(string protocol)
        {
            using (var server1 = new DealerSocket())
                using (var server2 = new DealerSocket())
                    using (var client = new DealerSocket())
                    {
                        string address2;

                        if (protocol == "tcp")
                        {
                            var port1 = server1.BindRandomPort("tcp://localhost");
                            var port2 = server2.BindRandomPort("tcp://localhost");

                            client.Connect("tcp://localhost:" + port1);
                            client.Connect("tcp://localhost:" + port2);

                            address2 = "tcp://localhost:" + port2;
                        }
                        else
                        {
                            server1.Bind("inproc://localhost1");
                            server2.Bind("inproc://localhost2");

                            client.Connect("inproc://localhost1");
                            client.Connect("inproc://localhost2");

                            address2 = "inproc://localhost2";
                        }

                        Thread.Sleep(100);

                        // we should be connected to both server
                        client.SendFrame("1");
                        client.SendFrame("2");

                        // make sure client is connected to both servers
                        server1.SkipFrame();
                        server2.SkipFrame();

                        // disconnect from server2, server 1 should receive all messages
                        client.Disconnect(address2);
                        Thread.Sleep(100);

                        client.SendFrame("1");
                        client.SendFrame("2");

                        server1.SkipFrame();
                        server1.SkipFrame();
                    }
        }
Пример #13
0
        public void RouterMandatoryFalseDiscardsMessageSilently()
        {
            {
                using (var dealer = new DealerSocket())
                {
                    dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer");
                    dealer.Bind("tcp://localhost:6667");

                    using (var router = new RouterSocket())
                    {
                        router.Connect("tcp://localhost:8889");

                        Assert.DoesNotThrow(() => router.SendMoreFrame("dealer").SendFrame("Hello"));
                    }
                }
            }
        }
Пример #14
0
        public void RouterMandatoryTrueThrowsHostUnreachableException()
        {
            {
                using (var dealer = new DealerSocket())
                {
                    dealer.Options.Identity = Encoding.ASCII.GetBytes("dealer");
                    dealer.Bind("tcp://localhost:6667");

                    using (var router = new RouterSocket())
                    {
                        router.Options.RouterMandatory = true;
                        router.Connect("tcp://localhost:8889");

                        Assert.Throws <HostUnreachableException>(() => router.SendMoreFrame("dealer").SendFrame("Hello"));
                    }
                }
            }
        }
Пример #15
0
        public void StartAgainAfterStop()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    // Send a message through to ensure the proxy has started
                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");
                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    proxy.Stop(); // blocks until stopped

                    // Start it again
                    Task.Factory.StartNew(proxy.Start);

                    // Send a message through to ensure the proxy has started
                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");
                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());
                        }

                    proxy.Stop(); // blocks until stopped
                }
        }
Пример #16
0
        public void Start()
        {
            using (_dealer = new DealerSocket())
            {
                _dealer.Bind(_dealerEndpoint);

                using (_router = new RouterSocket(_routerEndpoint))
                {
                    while (!_cancel.IsCancellationRequested)
                    {
                        var msg = _router.ReceiveMultipartMessage();

                        _dealer.SendFrame(msg[1].Buffer);

                        Handled++;
                    }
                }
            }
        }
Пример #17
0
        public void SeparateControlSocketsObservedMessages()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                    using (var controlInPush = new PushSocket())
                        using (var controlInPull = new PullSocket())
                            using (var controlOutPush = new PushSocket())
                                using (var controlOutPull = new PullSocket())
                                {
                                    front.Bind("inproc://frontend");
                                    back.Bind("inproc://backend");

                                    controlInPush.Bind("inproc://controlIn");
                                    controlInPull.Connect("inproc://controlIn");
                                    controlOutPush.Bind("inproc://controlOut");
                                    controlOutPull.Connect("inproc://controlOut");

                                    var proxy = new Proxy(front, back, controlInPush, controlOutPush);
                                    Task.Factory.StartNew(proxy.Start);

                                    using (var client = new RequestSocket())
                                        using (var server = new ResponseSocket())
                                        {
                                            client.Connect("inproc://frontend");
                                            server.Connect("inproc://backend");

                                            client.SendFrame("hello");
                                            Assert.AreEqual("hello", server.ReceiveFrameString());
                                            server.SendFrame("reply");
                                            Assert.AreEqual("reply", client.ReceiveFrameString());
                                        }

                                    Assert.IsNotNull(controlInPull.ReceiveFrameBytes()); // receive identity
                                    Assert.IsEmpty(controlInPull.ReceiveFrameString());  // pull terminator
                                    Assert.AreEqual("hello", controlInPull.ReceiveFrameString());

                                    Assert.IsNotNull(controlOutPull.ReceiveFrameBytes()); // receive identity
                                    Assert.IsEmpty(controlOutPull.ReceiveFrameString());  // pull terminator
                                    Assert.AreEqual("reply", controlOutPull.ReceiveFrameString());

                                    proxy.Stop();
                                }
        }
Пример #18
0
        public void StoppingProxyDisengagesFunctionality()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                {
                    front.Bind("inproc://frontend");
                    back.Bind("inproc://backend");

                    var proxy = new Proxy(front, back);
                    Task.Factory.StartNew(proxy.Start);

                    // Send a message through to ensure the proxy has started
                    using (var client = new RequestSocket())
                        using (var server = new ResponseSocket())
                        {
                            client.Connect("inproc://frontend");
                            server.Connect("inproc://backend");
                            client.SendFrame("hello");
                            Assert.AreEqual("hello", server.ReceiveFrameString());
                            server.SendFrame("reply");
                            Assert.AreEqual("reply", client.ReceiveFrameString());

                            proxy.Stop(); // blocks until stopped

                            using (var poller = new NetMQPoller {
                                front, back
                            })
                            {
                                poller.RunAsync();

                                client.SendFrame("anyone there?");

                                // Should no longer receive any messages
                                Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));
                            }
                        }
                }
        }
Пример #19
0
        public void TestProxySendAndReceiveWithExternalPoller()
        {
            using (var front = new RouterSocket())
                using (var back = new DealerSocket())
                    using (var poller = new NetMQPoller {
                        front, back
                    })
                    {
                        front.Bind("inproc://frontend");
                        back.Bind("inproc://backend");

                        var proxy = new Proxy(front, back, null, poller);

                        poller.RunAsync();

                        proxy.Start();

                        using (var client = new RequestSocket())
                            using (var server = new ResponseSocket())
                            {
                                client.Connect("inproc://frontend");
                                server.Connect("inproc://backend");

                                client.SendFrame("hello");
                                Assert.AreEqual("hello", server.ReceiveFrameString());
                                server.SendFrame("reply");
                                Assert.AreEqual("reply", client.ReceiveFrameString());

                                // Now stop the external poller
                                poller.Stop();

                                client.SendFrame("anyone there?");

                                // Should no longer receive any messages
                                Assert.IsFalse(server.TrySkipFrame(TimeSpan.FromMilliseconds(50)));
                            }
                    }
        }
Пример #20
0
        public void Unbind(string protocol)
        {
            using (var server = new DealerSocket())
            {
                string address1, address2;

                // just making sure can bind on both addresses
                using (var client1 = new DealerSocket())
                    using (var client2 = new DealerSocket())
                    {
                        if (protocol == "tcp")
                        {
                            var port1 = server.BindRandomPort("tcp://localhost");
                            var port2 = server.BindRandomPort("tcp://localhost");

                            address1 = "tcp://localhost:" + port1;
                            address2 = "tcp://localhost:" + port2;

                            client1.Connect(address1);
                            client2.Connect(address2);
                        }
                        else
                        {
                            Debug.Assert(protocol == "inproc");

                            address1 = "inproc://localhost1";
                            address2 = "inproc://localhost2";

                            server.Bind(address1);
                            server.Bind(address2);

                            client1.Connect(address1);
                            client2.Connect(address2);
                        }

                        Thread.Sleep(100);

                        // we should be connected to both server
                        client1.SendFrame("1");
                        client2.SendFrame("2");

                        // the server receive from both
                        server.SkipFrame();
                        server.SkipFrame();
                    }

                // unbind second address
                server.Unbind(address2);
                Thread.Sleep(100);

                using (var client1 = new DealerSocket())
                    using (var client2 = new DealerSocket())
                    {
                        client1.Options.DelayAttachOnConnect = true;
                        client1.Connect(address1);

                        client2.Options.DelayAttachOnConnect = true;

                        if (protocol == "tcp")
                        {
                            client2.Connect(address2);

                            client1.SendFrame("1");
                            server.SkipFrame();

                            Assert.IsFalse(client2.TrySendFrame(TimeSpan.FromSeconds(2), "2"));
                        }
                        else
                        {
                            Assert.Throws <EndpointNotFoundException>(() => { client2.Connect(address2); });
                        }
                    }
            }
        }
Пример #21
0
        public async Task <bool> RunSimulationAsync(Options options, TextWriter logger, CancellationToken token = default)
        {
            Logger = logger;
            try {
                Id = options.Id;

                _socket = new DealerSocket();
                _socket.Options.Linger   = TimeSpan.FromSeconds(30);
                _socket.Options.Identity = Encoding.ASCII.GetBytes(Id);
                if (options.Connect)
                {
                    _socket.Connect(options.URL);
                }
                else
                {
                    _socket.Bind(options.URL);
                }

                using (Outgoing = new NetMQQueue <NetMQMessage>()) {
                    using var poller = new NetMQPoller()
                          {
                              _socket, Outgoing
                          };
                    _socket.ReceiveReady += (sender, e) => {
                        var msg = _socket.ReceiveMultipartMessage();
                        if (msg.FrameCount < 3)
                        {
                            logger.WriteLine($"Received message with only {msg.FrameCount} frames.");
                            return;
                        }
                        var type = msg[1].ConvertToString();
                        logger.WriteLine($"Received {type} message.");
                        switch (type)
                        {
                        case "crane":
                            OnCraneMessageReceived(msg[2].Buffer);
                            break;

                        case "sim":
                            OnSimMessageReceived(msg[2].Buffer);
                            break;

                        default: //Console.WriteLine($"Received message with unmapped type {type}");
                            break;
                        }
                    };
                    Outgoing.ReceiveReady += (sender, e) => {
                        var msg = Outgoing.Dequeue();
                        if (_socket.TrySendMultipartMessage(TimeSpan.FromMinutes(1), msg)) // Note that for policyruns (virtual time) a lot of events are generated
                        {
                            logger.WriteLine($"Sent {msg[1].ConvertToString()} message.");
                        }
                        //else logger.WriteLine($"Discarded outgoing {msg[1].ConvertToString()} message.");
                    };

                    if (!options.RunSync || options.Connect)
                    {
                        poller.RunAsync();
                    }

                    if (!string.IsNullOrEmpty(options.SettingsPath))
                    {
                        if (options.SettingsPath.Equals("Default", StringComparison.OrdinalIgnoreCase))
                        {
                            logger.WriteLine("Using default settings");
                            _settingsReceived.SetResult(GetDefaultSettings());
                        }
                        else
                        {
                            logger.WriteLine($"Reading settings from {options.SettingsPath}");
                            _settingsReceived.SetResult(File.ReadAllBytes(options.SettingsPath));
                        }
                    }
                    var result = false;
                    try {
                        if (!options.RunSync)
                        {
                            result = await RunSimulationAsync(await _settingsReceived.Task, options.PolicyRun);

                            // wait until the outgoing queue is cleared
                            var remaining = Outgoing.Count;
                            while (remaining > 0)
                            {
                                await Task.Delay(1000, token);

                                if (Outgoing.Count == remaining)
                                {
                                    break;              // assume nobody is listening for world states
                                }
                                remaining = Outgoing.Count;
                            }
                        }
                        else
                        {
                            result = RunSimulation(await _settingsReceived.Task, options.SyncURL, options.Id);
                        }
                    } finally {
                        poller.Stop();
                    }
                    return(result);
                }
            } finally {
                DisposeSocket();
            }
        }