Example #1
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));
                }
            }
        }
            public void Send(String message)
            {
                using (var server = new DealerSocket())
                {
                    server.Options.Identity = Encoding.UTF8.GetBytes("CLIENT");

                    var ok = false;
                    do
                    {
                        try
                        {
                            server.Connect(_serverEndpoint);
                            ok = true;
                            Task.Delay(1000);
                        }
                        catch (NetMQException ex)
                        {
                        }
                    } while (!ok);


                    var msg = new NetMQMessage();
                    msg.AppendEmptyFrame();
                    msg.Append(message);

                    server.SendMultipartMessage(msg);

                    var result = server.ReceiveMultipartMessage();

                    var te = result[0];
                }
            }
Example #3
0
        private static void Client()
        {
            using (var sender = new DealerSocket())
            {
                sender.Options.Identity = Encoding.Unicode.GetBytes("salda".ToString());
                sender.Connect("tcp://127.0.0.1:9045");
                while (true)
                {
                    var message = new NetMQMessage();
                    message.Append("hello");
                    sender.SendMultipartMessage(message);
                    Console.WriteLine("Sent request");
                    //var response = sender.ReceiveMultipartMessage();
                    //Console.WriteLine("Received response");
                    //var itr = response.GetEnumerator();
                    //Console.WriteLine($"{(itr.MoveNext() ? "found" : "didn't find")} greeting frame");
                    //Console.WriteLine($"Greeting is: {itr.Current.ConvertToString()}");

                    var receiveFrameBytes = sender.ReceiveMultipartMessage();
                    using (var ms = new MemoryStream())
                    {
                        var equity = ProtoBufDeserialize <Equity>(receiveFrameBytes[0].Buffer, ms);
                        Console.WriteLine($"Equity: {equity.Value}");
                    }


                    Thread.Sleep(TimeSpan.FromSeconds(5));
                }
            }
        }
Example #4
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Klijent");
            Console.WriteLine("Unesite nick");
            string nick          = Console.ReadLine();
            string message       = string.Empty;
            string sendMessageTo = Console.ReadLine();

            using (var dealer = new DealerSocket())
            {
                dealer.Connect("tcp://127.0.0.1:5555");

                dealer.Options.Identity = Encoding.ASCII.GetBytes(nick);
                while (true)
                {
                    message = Console.ReadLine();
                    var msgToSrv = new NetMQMessage();
                    msgToSrv.Append(message);
                    msgToSrv.Append(nick);
                    dealer.SendMultipartMessage(msgToSrv);
                    //dealer.SendFrame(message);
                    var receiveFromServer = dealer.ReceiveMultipartMessage();
                    Console.WriteLine(receiveFromServer);
                }
            }
        }
Example #5
0
 private void MessageQueue_ReceiveReady(object sender, NetMQQueueEventArgs <NetMQMessage> e)
 {
     while (e.Queue.TryDequeue(out NetMQMessage messageToServer, TimeSpan.FromMilliseconds(10)))
     {
         client.SendMultipartMessage(messageToServer);
     }
 }
Example #6
0
        //Executes on same poller thread as dealer socket, so we can send directly
        private void SendQueue_ReceiveReady(object sender, NetMQQueueEventArgs <List <byte[]> > e)
        {
            var message = new NetMQMessage();

            message.AppendEmptyFrame();
            List <byte[]> frames;

            if (e.Queue.TryDequeue(out frames, new TimeSpan(1000)))
            {
                if (null != _session && null != _session.Crypto)
                {
                    //do not encrypt heartbeat message
                    if (frames.Count > 1 || !frames[0].IsEqualTo(MessageHeader.HeartBeat))
                    {
                        //encrypt message frames of regular messages but not heartbeat messages
                        for (int i = 0; i < frames.Count; i++)
                        {
                            frames[i] = _session.Crypto.Encrypt(frames[i]);
                        }
                    }
                }

                foreach (var frame in frames)
                {
                    message.Append(frame);
                }
                _dealerSocket.SendMultipartMessage(message);
                _logger.Debug("Message sent. Frame count: {0}", message.FrameCount);
            }
        }
Example #7
0
        private static void Main()
        {
            using (var frontend = new RouterSocket("@tcp://127.0.0.1:5559"))
            using (var backend = new DealerSocket("@tcp://127.0.0.1:5560"))
            {
                // Handler for messages coming in to the frontend
                frontend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    backend.SendMultipartMessage(msg); // Relay this message to the backend
                };

                // Handler for messages coming in to the backend
                backend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();
                    frontend.SendMultipartMessage(msg); // Relay this message to the frontend
                };

                using (var poller = new NetMQPoller {backend, frontend})
                {
                    // Listen out for events on both sockets and raise events when messages come in
                    poller.Run();
                }
            }
        }
Example #8
0
        private string SendRequest(string request)
        {
            using (var server = new DealerSocket())
            {
                server.Options.Identity = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());

                var ok = false;
                do
                {
                    try
                    {
                        server.Connect($"{_serverEndpoint}");
                        ok = true;
                    }
                    catch (NetMQException ex)
                    {
                    }
                } while (!ok);


                var msg = new NetMQMessage();
                msg.AppendEmptyFrame();
                msg.Append(request);

                server.SendMultipartMessage(msg);

                var result = server.ReceiveMultipartMessage();

                return(result[1].ConvertToString());
            }
        }
Example #9
0
        private static void Main()
        {
            using (var frontend = new RouterSocket("@tcp://127.0.0.1:5559"))
                using (var backend = new DealerSocket("@tcp://127.0.0.1:5560"))
                {
                    // Handler for messages coming in to the frontend
                    frontend.ReceiveReady += (s, e) =>
                    {
                        var msg = e.Socket.ReceiveMultipartMessage();
                        backend.SendMultipartMessage(msg); // Relay this message to the backend
                    };

                    // Handler for messages coming in to the backend
                    backend.ReceiveReady += (s, e) =>
                    {
                        var msg = e.Socket.ReceiveMultipartMessage();
                        frontend.SendMultipartMessage(msg); // Relay this message to the frontend
                    };

                    using (var poller = new NetMQPoller {
                        backend, frontend
                    })
                    {
                        // Listen out for events on both sockets and raise events when messages come in
                        poller.Run();
                    }
                }
        }
        public void RouterDealerMessaging()
        {
            using (var server = new RouterSocket())
                using (var client = new DealerSocket())
                {
                    int port = server.BindRandomPort("tcp://127.0.0.1");
                    client.Connect("tcp://127.0.0.1:" + port);

                    var clientOutgoingMessage = new NetMQMessage();
                    clientOutgoingMessage.Append("Hello");

                    client.SendMultipartMessage(clientOutgoingMessage);

                    NetMQMessage serverIncomingMessage = server.ReceiveMultipartMessage();

                    // number of frames should be one because first message should be identity of client
                    Assert.Equal(2, serverIncomingMessage.FrameCount);
                    Assert.Equal("Hello", serverIncomingMessage[1].ConvertToString());

                    var serverOutgoingMessage = new NetMQMessage();

                    // first adding the identity
                    serverOutgoingMessage.Append(serverIncomingMessage[0]);
                    serverOutgoingMessage.Append("World");

                    server.SendMultipartMessage(serverOutgoingMessage);

                    var incomingClientMessage = client.ReceiveMultipartMessage();

                    Assert.Equal(1, incomingClientMessage.FrameCount);
                    Assert.Equal("World", incomingClientMessage[0].ConvertToString());
                }
        }
Example #11
0
        public void ReceiveMultipartMessage()
        {
            async Task ReceiveAsync()
            {
                using (var server = new RouterSocket("inproc://async"))
                    using (var client = new DealerSocket("inproc://async"))
                    {
                        var req = new NetMQMessage();
                        req.Append("Hello");
                        req.Append(new byte[] { 0x00, 0x01, 0x02, 0x03 });

                        client.SendMultipartMessage(req);

                        NetMQMessage received = await server.ReceiveMultipartMessageAsync();

                        Assert.Equal("Hello", received[1].ConvertToString());
                        Assert.Equal(new byte[] { 0x00, 0x01, 0x02, 0x03 }, received[2].Buffer);
                    }
            }

            using (var runtime = new NetMQRuntime())
            {
                var t = ReceiveAsync();
                runtime.Run(t);

                if (t.IsFaulted && t.Exception is AggregateException exc)
                {
                    throw exc.GetBaseException();
                }
            }
        }
Example #12
0
        public void SendDealre(NetMQMessage message)
        {
            DealerSocket request = new DealerSocket();

            request.Connect(DealerAddress);
            request.SendMultipartMessage(message);
        }
Example #13
0
        public void AskForScenery()
        {
            var msg = new NetMQMessage();

            msg.Append((int)NetworkMessageType.ask);
            msg.Append((int)NetworkContentType.scenery_name);
            socket.SendMultipartMessage(msg);
        }
Example #14
0
        private void SendDebugMessage(string json)
        {
            var msg = new NetMQ.NetMQMessage();

            msg.Append(new byte[] { 6 });
            msg.Append(json);
            _socket.SendMultipartMessage(msg);
        }
        // Way OUT: Sending information
        public void Client_SendMsg(DealerSocket client, ChatMessage chatMessage)
        {
            var messageToServer = new NetMQMessage();

            messageToServer.AppendEmptyFrame();
            messageToServer.Append(chatMessage.ToJson(), Encoding.UTF8);

            client.SendMultipartMessage(messageToServer);
        }
Example #16
0
        static void Main(string[] args)
        {
            Process videoLoop = null;

            using (var responseSocket = new SubscriberSocket(">tcp://VideoApi:5557"))
                using (var requestSocket = new DealerSocket(">tcp://VideoApi:5558"))
                    using (var poller = new NetMQPoller {
                        responseSocket, requestSocket
                    })
                    {
                        requestSocket.Options.Identity = Encoding.ASCII.GetBytes(hostName);
                        // We are using NetMQ to retrieve the available devices in the following manner:
                        // queryRouterSocket -> querySocket -> All Devices In -> All Device out -> commandSocket -> queryRouterSocket
                        // Router            -> Publisher   -> Subscriber     -> Dealer         -> Router        -> Router
                        //This pattern allows any client to request the list of Clients in the commandSocket. So we can send messages directly to clients at another point in time.
                        responseSocket.Subscribe("All");
                        responseSocket.ReceiveReady += (o, e) =>
                        {
                            //Recieve a message to with the following fields:
                            // 1 - Subscription Name
                            // 2 - queryRouterSocket id
                            // 3 - command type
                            var msg     = e.Socket.ReceiveMultipartBytes();
                            var command = Encoding.UTF8.GetString(msg[2], 0, msg[2].Length);
                            if (command == "SendStatus")
                            {
                                var messageToServer = new NetMQMessage();
                                messageToServer.Append(msg[1]); //append the queryRouterSocket id so the caller knows where this msg should go.
                                var deviceStatus = new DeviceStatus()
                                {
                                    HostName = hostName, FriendlyName = friendlyName, StreamActive = (videoLoop != null)
                                };
                                messageToServer.Append(JsonConvert.SerializeObject(deviceStatus));
                                requestSocket.SendMultipartMessage(messageToServer);
                            }
                        };
                        requestSocket.ReceiveReady += (o, e) =>
                        {
                            var msg = e.Socket.ReceiveFrameString();
                            if (msg == "Start")
                            {
                                if (videoLoop == null)
                                {
                                    videoLoop = StartVideo();
                                }
                            }
                            else if (msg == "Stop")
                            {
                                StopVideo(videoLoop);
                                videoLoop = null;
                            }
                        };
                        poller.Run();
                    }
        }
Example #17
0
        public Tuple <string, string> Recognize(byte[] phrase)
        {
            var request = new NetMQMessage();

            request.Append(phrase);
            client.SendMultipartMessage(request);
            var response    = new NetMQMessage();
            var msgReceived = client.TryReceiveMultipartMessage(TimeSpan.FromSeconds(5), ref response);

            return(msgReceived ? ParseResponse(response) : new Tuple <string, string>("NoText", "Не удалось подключиться к серверу :("));
        }
Example #18
0
        static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Requires 3 arguments: SOCKET SIM_ID PROBLEM");
                return;
            }
            var socketAddr = args[0];
            var identity   = new UTF8Encoding().GetBytes(args[1]);
            //IPlanner planner = args[2] == "HS" ? new HotStorage.Planner() : new RollingMill.Planner();
            IPlanner planner = args[2] == "HS" ? new csharp.HS_Sync.SyncHSPlanner() : new RollingMill.Planner();

            OptimizerType optType;

            if (args.Length > 2)
            {
                optType = OptimizerType.RuleBased;
            }
            else
            {
                optType = OptimizerType.ModelBased;
            }

            Console.WriteLine(optType);

            using (var socket = new DealerSocket()) {
                socket.Options.Identity = identity;
                socket.Connect(socketAddr);
                Console.WriteLine("Connected");

                while (true)
                {
                    Console.WriteLine("Waiting for request...");
                    var request = socket.ReceiveMultipartBytes();
                    Console.WriteLine("Incoming request");
                    var answer = planner.PlanMoves(request[2], optType);

                    var msg = new NetMQMessage();
                    msg.AppendEmptyFrame();
                    msg.Append("crane");
                    if (answer != null)
                    {
                        msg.Append(answer);
                    }
                    else
                    {
                        msg.AppendEmptyFrame();
                    }

                    socket.SendMultipartMessage(msg);
                }
            }
        }
Example #19
0
 private void DealerSocket_SendReady(object sender, NetMQSocketEventArgs e)
 {
     while (!sendQueue.IsEmpty)
     {
         if (sendQueue.TryDequeue(out byte[] data))
         {
             var messageToServer = new NetMQMessage();
             messageToServer.AppendEmptyFrame();
             messageToServer.Append(data);
             dealerSocket.SendMultipartMessage(messageToServer);
         }
     }
 }
Example #20
0
        public Task <OwinResponse> SendAsync(OwinRequest request)
        {
            var taskCompletionSource = new TaskCompletionSource <OwinResponse>();

            using (NetMQSocket requestSocket = new DealerSocket($"inproc://{Identity}"))
            {
                NetMQMessage sendMessage = new NetMQMessage();
                sendMessage.AppendEmptyFrame();
                sendMessage.Append(_serializer.Serialize(request), Encoding.UTF8);
                requestSocket.SendMultipartMessage(sendMessage);
                _requests.AddOrUpdate(request.Id, taskCompletionSource, (key, value) => taskCompletionSource);
                return(taskCompletionSource.Task);
            }
        }
Example #21
0
        private async Task EstablishingConnectionAsync(NetMQMessage message, CancellationToken token)
        {
            try
            {
                _dealerSocket.SendMultipartMessage(message);

                var msg = await _dealerSocket.ReceiveMultipartMessageAsync(cancellationToken : token);

                Console.WriteLine($"From Server : {msg[1].ConvertToString()}");
            }
            catch (OperationCanceledException e)
            {
                Console.WriteLine("服务器无响应");
            }
        }
Example #22
0
        /// <summary>
        /// Asynchronously dispatches a request along the transport to the connected remote
        /// <see cref="NetMQReceiver"/> and returns a task that will complete when a response is returned from the
        /// remote or when the timeout elapses
        /// </summary>
        /// <param name="request">Request to send to the remote</param>
        /// <param name="timeout"><see cref="TimeSpan"/> after which the returned <see cref="Task{Message}"/> will throw an error if no response has been received</param>
        /// <returns>A task that will complete successfully when a response is received or that will fail once the timeout elapses</returns>
        public Task <object> SendAndReceive(object request, TimeSpan timeout)
        {
            if (disposedValue)
            {
                throw new InvalidOperationException("NetMQSender has been disposed");
            }

            if (!IsConnected)
            {
                throw new InvalidOperationException("NetMQSender is not connected");
            }

            return(taskManager.StartRemoteTask(requestId =>
            {
                var message = messageFactory.CreateRequestMessage(request, requestId);
                socket.SendMultipartMessage(message);
            }, timeout));
        }
Example #23
0
        void VentilatorCommand_SendCommand(DealerSocket ventilatorCommand, RouterSocket command)
        {
            #region communication ventilatorCommand  to Commander

            var msgCommand = new NetMQMessage();
            msgCommand.AppendEmptyFrame();
            msgCommand.Append("HELLO");
            ventilatorCommand.SendMultipartMessage(msgCommand);
            _testOutputHelper.WriteLine("Send Hello to command processor");

            Task.Delay(1000);

            var messageCommandID = command.ReceiveFrameString();
            command.ReceiveFrameString();
            var messageCommandCommand = command.ReceiveFrameString();
            _testOutputHelper.WriteLine("Received Command: {0} {1}", messageCommandID, messageCommandCommand);

            #endregion
        }
Example #24
0
        void VentilatorQuery_SendQuery(DealerSocket ventilatorQuery, RouterSocket query)
        {
            #region communication ventilatorQuery  to Querier

            var msgQuery = new NetMQMessage();
            msgQuery.AppendEmptyFrame();
            msgQuery.Append("HELLO");
            ventilatorQuery.SendMultipartMessage(msgQuery);
            _testOutputHelper.WriteLine("Send Hello to query processor");

            Task.Delay(1000);

            var messageQueryID = query.ReceiveFrameString();
            query.ReceiveFrameString();
            var messageQueryCommand = query.ReceiveFrameString();
            _testOutputHelper.WriteLine("Received Query: {0} {1}", messageQueryID, messageQueryCommand);

            #endregion
        }
Example #25
0
 public void Send(MSG msg, string toId = "", string head = "request")
 {
     try
     {
         if (!dealer.IsDisposed)
         {
             byte[]       byt   = ProtoBufHelp.Serialize <MSG>(msg);
             NetMQMessage mqmsg = new NetMQMessage(6);
             mqmsg.AppendEmptyFrame();
             mqmsg.Append("worker");
             mqmsg.Append(head);
             mqmsg.Append(ManagerHelp.ComponentId); //当前组件ID
             mqmsg.Append(toId);                    //下一级组件ID或上一级的组件ID
             mqmsg.Append(byt);
             //发送注册请求
             dealer.SendMultipartMessage(mqmsg);
         }
     }
     catch (Exception ex)
     {
     }
 }
Example #26
0
        private void OnFrontEndReady(object sender, NetMQSocketEventArgs e)
        {
            NetMQMessage message = _frontendSocket.ReceiveMultipartMessage();

            _backendSocket.SendMultipartMessage(message);
        }
Example #27
0
        void ClientCommand_Ventilator(DealerSocket client, RouterSocket ventilator, DealerSocket ventilatorCommand, RouterSocket command)
        {
            // inicialização das conexões ventilator -> command executor

            // var commandHello = new NetMQMessage();
            // commandHello.AppendEmptyFrame();
            // commandHello.Append("HELLO");
            // ventilatorCommand.SendMultipartMessage(commandHello);
            // _testOutputHelper.WriteLine("Send Hello to command processor");
            //
            // Task.Delay(1000);
            //
            // var hello = command.ReceiveFrameString();
            // command.ReceiveFrameString();
            // var helloCommand = command.ReceiveFrameString();
            // _testOutputHelper.WriteLine("Received Command: {0} {1}", hello, helloCommand);

            // client envia comando

            var commandData = new NetMQMessage();

            commandData.AppendEmptyFrame();
            commandData.Append("COMMAND");
            commandData.Append("COMMAND_DATA");
            client.SendMultipartMessage(commandData);
            _testOutputHelper.WriteLine("Client send a command to ventilator");

            Task.Delay(1000);

            var senderId = ventilator.ReceiveFrameString();

            ventilator.ReceiveFrameString();
            var requestType        = ventilator.ReceiveFrameString();
            var messageCommandData = ventilator.ReceiveFrameString();

            _testOutputHelper.WriteLine("Ventilator Received Request: {0} {1} {2}", senderId, requestType, messageCommandData);

            Task.Delay(1000);

            // ventilator roteia comando

            var routingCommandData = new NetMQMessage();

            routingCommandData.AppendEmptyFrame();
            routingCommandData.Append(messageCommandData);
            ventilatorCommand.SendMultipartMessage(routingCommandData);
            _testOutputHelper.WriteLine("Ventilator send a command to command processor");

            Task.Delay(1000);

            var sender = command.ReceiveFrameString();

            command.ReceiveFrameString();
            var receiveCommandData = command.ReceiveFrameString();

            _testOutputHelper.WriteLine("Command Received sender: {0} command args: {1}", sender, receiveCommandData);

            // Task.Delay(1000);
            //
            // var commandAnswerData = new NetMQMessage();
            // commandAnswerData.AppendEmptyFrame();
            // commandAnswerData.Append(messageCommandData + ": OK");
            // command.SendMultipartMessage(commandAnswerData);
            // _testOutputHelper.WriteLine("Command send an answer to ventilator");
            //
            // Task.Delay(1000);

            // var senderCommand = ventilatorCommand.ReceiveFrameString();
            // ventilatorCommand.ReceiveFrameString();
            // var receiveCommandAnswer = ventilatorCommand.ReceiveFrameString();
            // _testOutputHelper.WriteLine("Ventilator Received Command Answer: {0} command args: {1}", sender, receiveCommandAnswer);
            //
            // Task.Delay(1000);
            //
            // var routeAnswerData = new NetMQMessage();
            // routeAnswerData.AppendEmptyFrame();
            // routeAnswerData.Append(messageCommandData + ": OK");
            // ventilator.SendMultipartMessage(commandAnswerData);
            // _testOutputHelper.WriteLine("Command send an answer to ventilator");
            //
            // Task.Delay(1000);
            //
            // var senderCommand = ventilatorCommand.ReceiveFrameString();
            // ventilatorCommand.ReceiveFrameString();
            // var receiveCommandAnswer = ventilatorCommand.ReceiveFrameString();
            // _testOutputHelper.WriteLine("Ventilator Received Command Answer: {0} command args: {1}", sender, receiveCommandAnswer);
        }
Example #28
0
        public void Do()
        {
            using (var socket = new DealerSocket())
            {
                socket.Connect("tcp://127.0.0.1:5556");

                SecureChannel secureChannel = SecureChannel.CreateClientSecureChannel(null, m_configuration);

                // we are not using signed certificate so we need to validate
                // the certificate of the server, by default the secure channel
                // is checking that the source of the
                // certitiface is a root certificate authority
                //secureChannel.SetVerifyCertificate(c => true);

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

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

                // call the process message with null as the incoming message
                // because the client is initiating the connection
                secureChannel.ProcessMessage(null, outgoingMessages);
                //Server.SendMessages(socket, outgoingMessages);

                foreach (NetMQMessage message in outgoingMessages)
                {
                    socket.SendMultipartMessage(message);
                }
                outgoingMessages.Clear();
                // waiting for a message from the server
                NetMQMessage incomingMessage = socket.ReceiveMultipartMessage();

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

                foreach (NetMQMessage message in outgoingMessages)
                {
                    socket.SendMultipartMessage(message);
                }
                outgoingMessages.Clear();
                //Server.SendMessages(socket, outgoingMessages);
                // you can now use the secure channel to encrypt messages
                NetMQMessage plainMessage = new NetMQMessage();
                plainMessage.Append("Hello");

                // encrypting the message and sending it over the socket
                socket.SendMultipartMessage(secureChannel.EncryptApplicationMessage(plainMessage));
                NetMQMessage cipherMessage = socket.ReceiveMultipartMessage();

                // decrypting the message
                plainMessage = secureChannel.DecryptApplicationMessage(cipherMessage);
                System.Console.WriteLine(plainMessage.First.ConvertToString());
            }
        }
Example #29
0
        static void Main(string[] args)
        {
            var proxy1 = new Proxy(new RouterSocket("@tcp://*:5001"), new DealerSocket("@tcp://*:5002"));

            Task.Factory.StartNew(proxy1.Start);

            var dealer = new DealerSocket(">tcp://127.0.0.1:5002");
            var queue  = new NetMQQueue <NetMQMessage>();
            var poller = new NetMQPoller {
                dealer, queue
            };

            var show = false;

            dealer.ReceiveReady += (s, e) =>
            {
                var clientmessage = e.Socket.ReceiveMultipartMessage();

                Task.Factory.StartNew((o) =>
                {
                    var cmsg = (NetMQMessage)o;

                    var address = cmsg.First().ConvertToString();
                    var msg     = cmsg.Last().ConvertToString() + "-OK";

                    var servermessage = new NetMQMessage(3);
                    servermessage.Append(address);//fortest
                    servermessage.AppendEmptyFrame();
                    servermessage.Append(msg);


                    //var r = random.NextDouble();
                    //if (r > 0 && r < 0.78)
                    //{
                    //    Thread.Sleep(random.Next(1, 51));
                    //}
                    //else if (r >= 0.78 & r < 0.78 + 0.21)
                    //{
                    //    Thread.Sleep(random.Next(51, 101));
                    //}
                    //else
                    //{
                    //    Thread.Sleep(random.Next(101, 300));
                    //}

                    queue.Enqueue(servermessage);

                    //if (show)
                    //    Console.WriteLine(msg);
                }, clientmessage);

                if (show)
                {
                    Console.WriteLine(1);
                }
            };

            queue.ReceiveReady += (s, e) =>
            {
                var msg = e.Queue.Dequeue();

                dealer.SendMultipartMessage(msg);
            };

            poller.RunAsync();

            //for (var i = 0; i < 5; i++)
            //{
            //    Task.Factory.StartNew(() =>
            //    {
            //        while (true)
            //        {
            //            var servermessage = new NetMQMessage(3);
            //            servermessage.Append(Encoding.UTF8.GetBytes("dealerclient")); //for test
            //            servermessage.AppendEmptyFrame();
            //            servermessage.Append($"================={DateTime.Now.ToString()}======================");

            //            queue.Enqueue(servermessage);
            //            Thread.Sleep(1000);
            //        }
            //    });
            //}
            Console.WriteLine("Press any key to stop!");
            Console.Read();
            show = true;

            Console.Read();
            Console.Read();
            Console.Read();
        }
Example #30
0
        public void InprocRouterDealerTest()
        {
            // The main thread simply starts several clients and a server, and then
            // waits for the server to finish.
            var readyMsg    = Encoding.UTF8.GetBytes("RDY");
            var freeWorkers = new Queue <byte[]>();

            using (var backendsRouter = new RouterSocket())
            {
                backendsRouter.Options.Identity = Guid.NewGuid().ToByteArray();
                backendsRouter.Bind("inproc://backend");

                backendsRouter.ReceiveReady += (o, e) =>
                {
                    // Handle worker activity on backend
                    while (e.Socket.HasIn)
                    {
                        var msg      = e.Socket.ReceiveMultipartMessage();
                        var idRouter = msg.Pop();
                        // forget the empty frame
                        if (msg.First.IsEmpty)
                        {
                            msg.Pop();
                        }

                        var id = msg.Pop();
                        if (msg.First.IsEmpty)
                        {
                            msg.Pop();
                        }

                        if (msg.FrameCount == 1)
                        {
                            // worker send RDY message queue his Identity to the free workers queue
                            if (readyMsg[0] == msg[0].Buffer[0] &&
                                readyMsg[1] == msg[0].Buffer[1] &&
                                readyMsg[2] == msg[0].Buffer[2])
                            {
                                lock (freeWorkers)
                                {
                                    freeWorkers.Enqueue(id.Buffer);
                                }
                            }
                        }
                    }
                };

                using (var poller = new NetMQPoller {
                    backendsRouter
                })
                {
                    for (int i = 0; i < 2; i++)
                    {
                        ParameterizedThreadStart threadMmethod = state =>
                        {
                            byte[] routerId = (byte[])state;
                            byte[] workerId = Guid.NewGuid().ToByteArray();
                            using (var workerSocket = new DealerSocket())
                            {
                                workerSocket.Options.Identity = workerId;
                                workerSocket.Connect("inproc://backend");

                                var workerReadyMsg = new NetMQMessage();
                                workerReadyMsg.Append(workerId);
                                workerReadyMsg.AppendEmptyFrame();
                                workerReadyMsg.Append(readyMsg);
                                workerSocket.SendMultipartMessage(workerReadyMsg);
                                Thread.Sleep(1000);
                            }
                        };

                        var workerThread = new Thread(threadMmethod)
                        {
                            IsBackground = true,
                            Name         = "worker" + i
                        };

                        workerThread.Start(backendsRouter.Options.Identity);
                    }

                    poller.RunAsync();
                    Thread.Sleep(1000);
                    poller.Stop();
                    Assert.AreEqual(2, freeWorkers.Count);
                }
            }
        }
Example #31
0
 /// <summary>
 /// Sends the message to the event bus using dealer socket.
 /// </summary>
 /// <param name="message">Message to be sent.</param>
 public void SendMessage(NetMQMessage message)
 {
     _dealerSocket.SendMultipartMessage(message);
 }