Esempio n. 1
0
        private static void Server()
        {
            using (var receiver = new RouterSocket())
            {
                receiver.Bind("tcp://*:9045");
                while (true)
                {
                    var message = receiver.ReceiveMultipartMessage();
                    Console.WriteLine("Received request for equity");
                    //var itr = message.GetEnumerator();
                    //Console.WriteLine($"{(itr.MoveNext() ? "found" : "didn't find")} identity frame");
                    //Console.Write($"from {itr.Current.ConvertToString(Encoding.Unicode)}");

                    var response = new NetMQMessage();
                    response.Append(message.First);
                    //response.Append("goodbye");
                    //receiver.SendMultipartMessage(response);
                    //Console.WriteLine("Sent response.");
                    using (var ms = new MemoryStream())
                    {
                        var equity = ProtoBufSerialize(new Equity()
                        {
                            Account = new Account(), AccountID = 1, ID = 1, UpdateTime = DateTime.Now, Value = 500000
                        }, ms);

                        response.Append(equity);
                        response.AppendEmptyFrame();
                        receiver.SendMultipartMessage(response);
                    }
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        ///     Starts the server.
        /// </summary>
        public void StartServer()
        {
            using (routerSocket)
            {
                Thread.Sleep(10000);
                logger.Log(LogLevel.Info, $"Trying to bind to {routerConnectionString}");
                routerSocket.Bind(routerConnectionString);
                running = true;
                logger.Log(LogLevel.Info, $"Router socket successfully binded on {routerConnectionString}");
                Console.WriteLine($"Server is bind to {routerConnectionString}");
                while (running)
                {
                    logger.Log(LogLevel.Info, $"Router socket is waiting on message on {routerConnectionString}");
                    var message   = routerSocket.ReceiveMultipartMessage();
                    var accountID = message[2].ConvertToInt32();
                    logger.Log(LogLevel.Info, $"Received request for equity on account ID:{accountID}");

                    var response = new NetMQMessage();

                    using (var ms = new MemoryStream())
                    {
                        var input  = new MyDBContext().Equity.FromSql($"SELECT value FROM dbo.Equity WHERE AccountID={accountID}").Last();
                        var equity = MyUtils.ProtoBufSerialize(input, ms);
                        response.Append(message[0]);
                        response.AppendEmptyFrame();
                        response.Append(equity);
                        routerSocket.SendMultipartMessage(response);
                    }
                }
            }
        }
        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());
                }
        }
Esempio n. 4
0
        private async Task HandleStateOfTheWorldRequest()
        {
            using (_stateRequestSocket = new RouterSocket())
            {
                _stateRequestSocket.Bind(_configuration.StateOftheWorldEndpoint);

                while (!_cancel.IsCancellationRequested)
                {
                    var message = _stateRequestSocket.ReceiveMultipartMessage();
                    var sender  = message[0].Buffer;
                    var request = _serializer.Deserialize <IStateRequest>(message[1].Buffer);

                    var stream = await _cache.GetStreamBySubject(request.Subject);

                    var response = new StateReply()
                    {
                        Subject = request.Subject,
                        Events  = stream.ToList()
                    };

                    _stateRequestSocket.SendMoreFrame(sender)
                    .SendFrame(_serializer.Serialize(response));
                }
            }
        }
        private void HandleHeartbeat()
        {
            _heartbeatSocket = new RouterSocket(_producerConfiguration.HeartbeatEnpoint);

            while (!_cancel.IsCancellationRequested)
            {
                var message      = _heartbeatSocket.ReceiveMultipartMessage();
                var messageBytes = message[2].Buffer;

                var heartbeat = JsonConvert.DeserializeObject <HeartbeatQuery>(Encoding.UTF32.GetString(messageBytes), _settings);

                using (var sender = new RequestSocket(heartbeat.HeartbeatEndpoint))
                {
                    var heartbeatResponse = new HeartbeatResponse()
                    {
                        ProducerId = _producerConfiguration.Id,
                        Now        = DateTime.Now
                    };

                    var msg = Encoding.UTF32.GetBytes(JsonConvert.SerializeObject(heartbeatResponse, _settings));

                    sender.SendFrame(msg);

                    Task.Delay(200).Wait();
                }
            }
        }
Esempio n. 6
0
 static void Main(string[] args)
 {
     using (var server = new RouterSocket("@tcp://127.0.0.1:5000"))
     {
         while (true)
         {
             Console.WriteLine("Server waiting for message");
             var clientMessage = server.ReceiveMultipartMessage();
             Console.WriteLine("======================================");
             Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");
             Console.WriteLine("======================================");
             PrintFrames("Server receiving", clientMessage);
             if (clientMessage.FrameCount == 3)
             {
                 var    clientAddress         = clientMessage[0];
                 var    clientOriginalMessage = clientMessage[2].ConvertToString();
                 string response = string.Format("{0} back from server {1}",
                                                 clientOriginalMessage, DateTime.Now.ToLongTimeString());
                 var messageToClient = new NetMQMessage();
                 messageToClient.Append(clientAddress);
                 messageToClient.AppendEmptyFrame();
                 messageToClient.Append(response);
                 server.SendMultipartMessage(messageToClient);
             }
         }
     }
 }
Esempio n. 7
0
        static void RunServer(CancellationToken cancellationToken)
        {
            Task.Factory.StartNew(() =>
            {
                var random = new Random();
                using (var server = new RouterSocket())
                {
                    server.Bind("tcp://*:5555");
                    Console.WriteLine("\t\t\tServer: Bound to *:5555");

                    while (!cancellationToken.IsCancellationRequested)
                    {
                        var request = server.ReceiveMultipartMessage();
                        var message = request[2].ConvertToString();

                        Console.WriteLine($"\t\t\tServer: Received {message}");

                        // Simulate work
                        Thread.Sleep(200);

                        var responsestr = $"World {random.Next(100)}";
                        Console.WriteLine($"\t\t\tServer: Sending {responsestr}");

                        var response = new NetMQMessage();
                        response.Append(request[0]);
                        response.AppendEmptyFrame();
                        response.Append(responsestr);
                        response.AppendEmptyFrame();
                        server.SendMultipartMessage(response);
                    }
                }
            });
        }
Esempio n. 8
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Server");
            using (var router = new RouterSocket())
            {
                router.Options.RouterMandatory = true;
                router.Bind("tcp://127.0.0.1:5555");

                bool more = false;
                while (true)
                {
                    //string a = router.ReceiveFrameString(Encoding.ASCII,out more);
                    //var nick = router.Options.Identity;

                    //Console.WriteLine(nick);
                    //Console.WriteLine(a);

                    var clientMessage = router.ReceiveMultipartMessage();
                    PrintFrames("Server receiving", clientMessage);


                    var msgToClient = new NetMQMessage();
                    msgToClient.Append(clientMessage[0]);
                    msgToClient.Append(clientMessage[1]);
                    msgToClient.Append(clientMessage[2]);

                    router.SendMultipartMessage(msgToClient);
                }
            }
        }
Esempio n. 9
0
        public static IdKeyData RouterReceive(this RouterSocket socket)
        {
            IdKeyData    ikd = new IdKeyData();
            NetMQMessage msg = socket.ReceiveMultipartMessage();

            ikd.Id  = msg[0].ConvertToString(); //socket.Options.Identity
            ikd.Key = msg[2].ConvertToString();
            byte[] zipData = msg[3].Buffer;
            ikd.Data = GZipUtil.Decompress(zipData);

            return(ikd);
        }
Esempio n. 10
0
        public void Issue52_ReqToRouterBug()
        {
            using (var router = new RouterSocket())
                using (var req = new RequestSocket())
                {
                    router.Bind("inproc://example");
                    req.Connect("inproc://example");

                    const string testmessage = "Simple Messaging Test";

                    req.SendFrame(testmessage);

                    var msg = router.ReceiveMultipartMessage();
                    Assert.Equal(3, msg.FrameCount);
                    Assert.Equal(msg[2].ConvertToString(), testmessage);
                }
        }
Esempio n. 11
0
 private void ServerLoop()
 {
     while (true)
     {
         var clientMessage = routerSocket.ReceiveMultipartMessage();
         if (clientMessage.FrameCount == 3)
         {
             var clientAddress   = clientMessage[0];
             var sendData        = OnReceive(clientMessage[2].ToByteArray());
             var messageToClient = new NetMQMessage();
             messageToClient.Append(clientAddress);
             messageToClient.AppendEmptyFrame();
             messageToClient.Append(sendData);
             routerSocket.SendMultipartMessage(messageToClient);
         }
     }
 }
Esempio n. 12
0
        private void StartExternalEndpoint()
        {
            using (var server = new RouterSocket())
            {
                server.Options.Identity        = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
                server.Options.RouterMandatory = true;
                server.Bind($"{_externalEndpoint}");

                server.ReceiveReady += (sender, args) =>
                {
                    // está se conectando em mim então eu posso me conectar de volta.

                    // var id = args.Socket.ReceiveFrameString();
                    // var comando = args.Socket.ReceiveFrameString();
                    // var empty = args.Socket.ReceiveFrameString();
                    // var dados = args.Socket.ReceiveFrameString();
                };

                try
                {
                    while (true)
                    {
                        var message = server.ReceiveMultipartMessage();

                        var json = message[2].ConvertToString();


                        //TODO: Executar a query e retornar

                        var response = Handle(JsonSerializer.Deserialize <TQuery>(json));

                        var messageToRouter = new NetMQMessage();
                        messageToRouter.Append(message[0]);
                        messageToRouter.AppendEmptyFrame();
                        messageToRouter.Append(JsonSerializer.Serialize(response));

                        server.SendMultipartMessage(messageToRouter);
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 13
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++;
                    }
                }
            }
        }
Esempio n. 14
0
        public override bool Start(string port = "33000")
        {
            bool hasStarted = true;

            try
            {
                using (var router = new RouterSocket($"@tcp://127.0.0.1:{port}"))
                {
                    LOG(LogLevel.VERBOSE, $"[SERVER] started at port:{port}");
                    LOG(LogLevel.DEBUG, "We are in DEBUG mode");

                    ServerInternalPublisher pub = new ServerInternalPublisher();
                    var sub = new ServerInternalSubscriber(router, port, pub);

                    // server continuous loop
                    while (true)
                    {
                        var clientMQMessage = router.ReceiveMultipartMessage();

                        if (clientMQMessage.HasExpectedFrames())
                        {
                            var envelope = clientMQMessage.GetChatEnvelope();

                            pub.Deliver(envelope);
                        }
                    }
                }
            }
            catch (AddressAlreadyInUseException)
            {
                //LOG(LogLevel.WARNING, $"[WARNING]: Address already in use");
                hasStarted = false;
            }
            catch (Exception ex)
            {
                LOG(LogLevel.ERROR, $"[EXCEPTION]: {ex.ToString()}");
                throw;
            }

            return(hasStarted);
        }
Esempio n. 15
0
        public void Run()
        {
            while (true)
            {
                var request = server.ReceiveMultipartMessage();
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Received a message from client at " + DateTime.Now);
                Console.ForegroundColor = ConsoleColor.White;
                var response      = new NetMQMessage();
                var clientAddress = request[0];
                response.Append(clientAddress);

                var phrase = recognizer.Recognize(request[1].ToByteArray());
                var result = parser.ParsePhrase(phrase);
                server.SendMultipartMessage(CreateResponse(response, result));
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Sent a message with header: " + response[1].ConvertToString(Encoding.UTF8) + " at " +
                                  DateTime.Now);
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Esempio n. 16
0
        public DealerRouter()
        {
            const int delay = 3000;

            //Keep dealersocket reference within each three threads
            var clientSocketPerThread = new ThreadLocal <DealerSocket>();


            using (var server = new RouterSocket("tcp://127.0.0.1:5556"))
                using (var poller = new NetMQPoller())
                {
                    for (int i = 0; i < 3; i++)
                    {
                        Task.Factory.StartNew(state =>
                        {
                            DealerSocket client = null;

                            if (!clientSocketPerThread.IsValueCreated)
                            {
                                client = new DealerSocket();
                                client.Options.Identity = Encoding.Unicode.GetBytes(state.ToString());
                                client.Connect("tcp://127.0.0.1:5556");
                                client.ReceiveReady        += Client_ReceivedReady;
                                clientSocketPerThread.Value = client;
                                poller.Add(client);
                            }
                            else
                            {
                                client = clientSocketPerThread.Value;
                            }

                            //the dealersocket will provide an identity for message when it is created
                            while (true)
                            {
                                var messageToServer = new NetMQMessage();
                                messageToServer.AppendEmptyFrame();
                                messageToServer.Append(state.ToString());
                                Console.WriteLine("======================================");
                                Console.WriteLine(" OUTGOING MESSAGE TO SERVER ");
                                Console.WriteLine("======================================");
                                PrintFrames("Client Sending", messageToServer);
                                client.SendMultipartMessage(messageToServer);
                                Thread.Sleep(delay);
                            }
                        }, string.Format("client {0}", i), TaskCreationOptions.LongRunning);
                    }
                    poller.RunAsync();

                    while (true)
                    {
                        var clientMessage = server.ReceiveMultipartMessage();
                        Console.WriteLine("======================================");
                        Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");
                        Console.WriteLine("======================================");
                        PrintFrames("Server receiving", clientMessage);

                        if (clientMessage.FrameCount == 3)
                        {
                            var    clientAddress         = clientMessage[0];
                            var    clientOriginalMessage = clientMessage[2].ConvertToString();
                            string response = string.Format("{0} back from server {1} address {2}",
                                                            clientOriginalMessage, DateTime.Now.ToLongTimeString(), clientAddress.ConvertToString());
                            var messageToClient = new NetMQMessage();
                            messageToClient.Append(clientAddress);
                            messageToClient.AppendEmptyFrame();
                            messageToClient.Append(response);
                            server.SendMultipartMessage(messageToClient);
                        }
                    }
                }
        }
Esempio n. 17
0
        public static void Main(string[] args)
        {
            // NOTES
            // 1. Use ThreadLocal&lt;DealerSocket&gt; where each thread has
            //    its own client DealerSocket to talk to server
            // 2. Each thread can send using it own socket
            // 3. Each thread socket is added to poller

            const int delay = 3000; // millis

            var clientSocketPerThread = new ThreadLocal <DealerSocket> ();

            using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
                using (var poller = new NetMQPoller())
                {
                    // Start some threads, each with its own DealerSocket
                    // to talk to the server socket. Creates lots of sockets,
                    // but no nasty race conditions no shared state, each
                    // thread has its own socket, happy days.
                    for (int i = 0; i < 3; i++)
                    {
                        Task.Factory.StartNew(state =>
                        {
                            DealerSocket client = null;

                            if (!clientSocketPerThread.IsValueCreated)
                            {
                                client = new DealerSocket();
                                client.Options.Identity =
                                    Encoding.Unicode.GetBytes(state.ToString());
                                client.Connect("tcp://127.0.0.1:5556");
                                client.ReceiveReady        += Client_ReceiveReady;
                                clientSocketPerThread.Value = client;
                                poller.Add(client);
                            }
                            else
                            {
                                client = clientSocketPerThread.Value;
                            }

                            while (true)
                            {
                                var messageToServer = new NetMQMessage();
                                messageToServer.AppendEmptyFrame();
                                messageToServer.Append(state.ToString());
                                Console.WriteLine("======================================");
                                Console.WriteLine(" OUTGOING MESSAGE TO SERVER ");
                                Console.WriteLine("======================================");
                                PrintFrames("Client Sending", messageToServer);
                                client.SendMultipartMessage(messageToServer);
                                Thread.Sleep(delay);
                            }
                        }, string.Format("client {0}", i), TaskCreationOptions.LongRunning);
                    }

                    // start the poller
                    poller.RunAsync();

                    // server loop
                    while (true)
                    {
                        var clientMessage = server.ReceiveMultipartMessage();
                        Console.WriteLine("======================================");
                        Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");
                        Console.WriteLine("======================================");
                        PrintFrames("Server receiving", clientMessage);
                        if (clientMessage.FrameCount == 3)
                        {
                            var    clientAddress         = clientMessage[0];
                            var    clientOriginalMessage = clientMessage[2].ConvertToString();
                            string response = string.Format("{0} back from server {1}",
                                                            clientOriginalMessage, DateTime.Now.ToLongTimeString());
                            var messageToClient = new NetMQMessage();
                            messageToClient.Append(clientAddress);
                            messageToClient.AppendEmptyFrame();
                            messageToClient.Append(response);
                            server.SendMultipartMessage(messageToClient);
                        }
                    }
                }
            void PrintFrames(string operationType, NetMQMessage message)
            {
                for (int i = 0; i < message.FrameCount; i++)
                {
                    Console.WriteLine("{0} Socket : Frame[{1}] = {2}", operationType, i,
                                      message[i].ConvertToString());
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// ParanoidPirate.Queue [-v]
        ///
        /// Does load-balancing with heartbeating on worker tasks to detect
        /// crashed, blocked or slow running worker tasks    .
        /// </summary>
        private static void Main(string[] args)
        {
            Console.Title = "NetMQ ParanoidPirate Queue";

            // serves as flag for exiting the program
            var exit = false;

            // catch CTRL+C as exit command
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                exit     = true;
            };

            var verbose = args.Length > 0 && args[0] == "-v";

            using (var frontend = new RouterSocket())
                using (var backend = new RouterSocket())
                    using (var poller = new NetMQPoller())
                    {
                        frontend.Bind(Commons.QueueFrontend);
                        backend.Bind(Commons.QueueBackend);

                        var workers = new Workers();

                        // client sends to this socket
                        frontend.ReceiveReady += (s, e) =>
                        {
                            // only process incoming client requests
                            // if we have workers available handle client requests as long as we have workers
                            // storage capability of the socket otherwise and pick up later
                            if (workers.Available)
                            {
                                // get all message frames!
                                var request = frontend.ReceiveMultipartMessage();

                                if (verbose)
                                {
                                    Console.WriteLine("[QUEUE] received {0}", request);
                                }

                                // get next available worker
                                var worker = workers.Next();
                                // wrap message with worker's address
                                var msg = Wrap(worker, request);

                                if (verbose)
                                {
                                    Console.WriteLine("[QUEUE -> WORKER] sending {0}", msg);
                                }

                                backend.SendMultipartMessage(msg);
                            }
                        };

                        // worker sends to this socket
                        backend.ReceiveReady += (s, e) =>
                        {
                            var msg = e.Socket.ReceiveMultipartMessage();

                            if (verbose)
                            {
                                Console.WriteLine("[QUEUE <- WORKER] received {0}", msg);
                            }

                            // use workers identity for load-balancing
                            var workerIdentity = Unwrap(msg);
                            var worker         = new Worker(workerIdentity);
                            workers.Ready(worker);
                            // just convenience
                            var readableWorkerId = workerIdentity.ConvertToString();

                            if (msg.FrameCount == 1)
                            {
                                var data = msg[0].ConvertToString();
                                // the message is either READY or HEARTBEAT or corrupted
                                switch (data)
                                {
                                case Commons.PPPHeartbeat:
                                    Console.WriteLine("[QUEUE <- WORKER] Received a Heartbeat from {0}",
                                                      readableWorkerId);
                                    break;

                                case Commons.PPPReady:
                                    Console.WriteLine("[QUEUE <- WORKER] Received a READY form {0}",
                                                      readableWorkerId);
                                    break;

                                default:
                                    Console.WriteLine("[QUEUE <- WORKER] ERROR received an invalid message!");
                                    break;
                                }
                            }
                            else
                            {
                                if (verbose)
                                {
                                    Console.WriteLine("[QUEUE -> CLIENT] sending {0}", msg);
                                }

                                frontend.SendMultipartMessage(msg);
                            }
                        };

                        var timer = new NetMQTimer(Commons.HeartbeatInterval);
                        // every specified ms QUEUE shall send a heartbeat to all connected workers
                        timer.Elapsed += (s, e) =>
                        {
                            // send heartbeat to every worker
                            foreach (var worker in workers)
                            {
                                var heartbeat = new NetMQMessage();

                                heartbeat.Push(new NetMQFrame(Commons.PPPHeartbeat));
                                heartbeat.Push(worker.Identity);

                                Console.WriteLine("[QUEUE -> WORKER] sending heartbeat!");

                                backend.SendMultipartMessage(heartbeat);
                            }
                            // restart timer
                            e.Timer.Enable = true;
                            // remove all dead or expired workers
                            workers.Purge();
                        };

                        if (verbose)
                        {
                            Console.WriteLine("[QUEUE] Start listening!");
                        }

                        poller.Add(frontend);
                        poller.Add(backend);

                        poller.RunAsync();

                        // hit CRTL+C to stop the while loop
                        while (!exit)
                        {
                            Thread.Sleep(100);
                        }
                    }
        }
Esempio n. 19
0
        /// <summary>
        /// ParanoidPirate.Queue [-v]
        ///
        /// Does load-balancing with heartbeating on worker tasks to detect
        /// crashed, blocked or slow running worker tasks    .
        /// </summary>
        private static void Main(string[] args)
        {
            Console.Title = "NetMQ ParanoidPirate Queue";

            // serves as flag for exiting the program
            var exit = false;
            // catch CTRL+C as exit command
            Console.CancelKeyPress += (s, e) =>
            {
                e.Cancel = true;
                exit = true;
            };

            var verbose = args.Length > 0 && args[0] == "-v";

            using (var frontend = new RouterSocket())
            using (var backend = new RouterSocket())
            using (var poller = new NetMQPoller())
            {
                frontend.Bind(Commons.QueueFrontend);
                backend.Bind(Commons.QueueBackend);

                var workers = new Workers();

                // client sends to this socket
                frontend.ReceiveReady += (s, e) =>
                {
                    // only process incoming client requests
                    // if we have workers available handle client requests as long as we have workers
                    // storage capability of the socket otherwise and pick up later
                    if (workers.Available)
                    {
                        // get all message frames!
                        var request = frontend.ReceiveMultipartMessage();

                        if (verbose)
                            Console.WriteLine("[QUEUE] received {0}", request);

                        // get next available worker
                        var worker = workers.Next();
                        // wrap message with worker's address
                        var msg = Wrap(worker, request);

                        if (verbose)
                            Console.WriteLine("[QUEUE -> WORKER] sending {0}", msg);

                        backend.SendMultipartMessage(msg);
                    }
                };

                // worker sends to this socket
                backend.ReceiveReady += (s, e) =>
                {
                    var msg = e.Socket.ReceiveMultipartMessage();

                    if (verbose)
                        Console.WriteLine("[QUEUE <- WORKER] received {0}", msg);

                    // use workers identity for load-balancing
                    var workerIdentity = Unwrap(msg);
                    var worker = new Worker(workerIdentity);
                    workers.Ready(worker);
                    // just convenience
                    var readableWorkerId = workerIdentity.ConvertToString();

                    if (msg.FrameCount == 1)
                    {
                        var data = msg[0].ConvertToString();
                        // the message is either READY or HEARTBEAT or corrupted
                        switch (data)
                        {
                            case Commons.PPPHeartbeat:
                                Console.WriteLine("[QUEUE <- WORKER] Received a Heartbeat from {0}",
                                    readableWorkerId);
                                break;
                            case Commons.PPPReady:
                                Console.WriteLine("[QUEUE <- WORKER] Received a READY form {0}",
                                    readableWorkerId);
                                break;
                            default:
                                Console.WriteLine("[QUEUE <- WORKER] ERROR received an invalid message!");
                                break;
                        }
                    }
                    else
                    {
                        if (verbose)
                            Console.WriteLine("[QUEUE -> CLIENT] sending {0}", msg);

                        frontend.SendMultipartMessage(msg);
                    }
                };

                var timer = new NetMQTimer(Commons.HeartbeatInterval);
                // every specified ms QUEUE shall send a heartbeat to all connected workers
                timer.Elapsed += (s, e) =>
                {
                    // send heartbeat to every worker
                    foreach (var worker in workers)
                    {
                        var heartbeat = new NetMQMessage();

                        heartbeat.Push(new NetMQFrame(Commons.PPPHeartbeat));
                        heartbeat.Push(worker.Identity);

                        Console.WriteLine("[QUEUE -> WORKER] sending heartbeat!");

                        backend.SendMultipartMessage(heartbeat);
                    }
                    // restart timer
                    e.Timer.Enable = true;
                    // remove all dead or expired workers
                    workers.Purge();
                };

                if (verbose)
                    Console.WriteLine("[QUEUE] Start listening!");

                poller.Add(frontend);
                poller.Add(backend);

                poller.RunAsync();

                // hit CRTL+C to stop the while loop
                while (!exit)
                    Thread.Sleep(100);
            }
        }
Esempio n. 20
0
        public static void Main(string[] args)
        {
            string tcp    = "tcp://127.0.0.1:20000";
            string inproc = "inproc://response_dealer";

            ResponseSocket res = new ResponseSocket(inproc);

            IpcCollectorDevice ipcCollectorDevice = new IpcCollectorDevice(tcp, inproc);

            ipcCollectorDevice.Start();

            NetMQRequestor requestor = new NetMQRequestor(tcp);
            var            message   = Guid.NewGuid().ToString();

            requestor.SendMessage(message);
            // NOTES
            // 1. Use ThreadLocal&lt;DealerSocket&gt; where each thread has
            //    its own client DealerSocket to talk to server
            // 2. Each thread can send using it own socket
            // 3. Each thread socket is added to poller

            const int delay = 10; // millis

            var clientSocketPerThread = new ThreadLocal <DealerSocket>();
            int d = 0;

            using (var server = new RouterSocket("@tcp://127.0.0.1:5556"))
                using (var poller = new NetMQPoller())
                {
                    // Start some threads, each with its own DealerSocket
                    // to talk to the server socket. Creates lots of sockets,
                    // but no nasty race conditions no shared state, each
                    // thread has its own socket, happy days.
                    for (int i = 0; i < 3; i++)
                    {
                        Task.Factory.StartNew(state =>
                        {
                            DealerSocket client = null;

                            if (!clientSocketPerThread.IsValueCreated)
                            {
                                client = new DealerSocket();
                                client.Options.Identity =
                                    Encoding.Unicode.GetBytes(state.ToString());
                                client.Connect("tcp://127.0.0.1:5556");
                                client.ReceiveReady        += Client_ReceiveReady;
                                clientSocketPerThread.Value = client;
                                poller.Add(client);
                            }
                            else
                            {
                                client = clientSocketPerThread.Value;
                            }

                            while (true)
                            {
                                var messageToServer = new NetMQMessage();
                                messageToServer.AppendEmptyFrame();
                                messageToServer.Append(Interlocked.Increment(ref d).ToString());
                                //Console.WriteLine("======================================");
                                //Console.WriteLine(" OUTGOING MESSAGE TO SERVER ");
                                //Console.WriteLine("======================================");
                                //PrintFrames("Client Sending", messageToServer);
                                //messageToServer.ToString();
                                client.SendMultipartMessage(messageToServer);
                                Thread.Sleep(delay);
                            }
                        }, string.Format("client {0}", i), TaskCreationOptions.LongRunning);
                    }

                    // start the poller
                    poller.RunAsync();

                    // server loop
                    while (true)
                    {
                        string date          = DateTime.Now.ToString();
                        var    clientMessage = server.ReceiveMultipartMessage();
                        //Console.WriteLine("======================================");
                        //Console.WriteLine(" INCOMING CLIENT MESSAGE FROM CLIENT ");
                        //Console.WriteLine("======================================");
                        //PrintFrames("Server receiving", clientMessage);
                        Thread.Sleep(new Random().Next(0, 1000));
                        if (clientMessage.FrameCount == 3)
                        {
                            var    clientAddress         = clientMessage[0];
                            var    clientOriginalMessage = clientMessage[2].ConvertToString();
                            string response        = string.Format("{0} back from server {1}", clientOriginalMessage, date);
                            var    messageToClient = new NetMQMessage();
                            messageToClient.Append(clientAddress);
                            messageToClient.AppendEmptyFrame();
                            messageToClient.Append(response);
                            server.SendMultipartMessage(messageToClient);
                        }
                    }
                }
        }
Esempio n. 21
0
        private void OnFrontEndReady(object sender, NetMQSocketEventArgs e)
        {
            NetMQMessage message = _frontendSocket.ReceiveMultipartMessage();

            _backendSocket.SendMultipartMessage(message);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Tier 2");

            var reciveSocket = new ResponseSocket();
            //reciveSocket.Bind("tcp://0.0.0.0:" + listeningPort);



            var newRouterSocket = new RouterSocket();

            newRouterSocket.Bind("tcp://0.0.0.0:" + listeningPort);

            Console.WriteLine("Ready to recive!");

            var message = newRouterSocket.ReceiveMultipartMessage();

            var sendSocket = new RequestSocket();

            sendSocket.Connect("tcp://127.0.0.1:" + net_mq_tier_three.Program.listeningPort);



            List <NetMQFrame> frames = new List <NetMQFrame>();

            while (false == message.IsEmpty)
            {
                var frame = message.Pop();
                frames.Add(frame);
            }

            if ("MethidID" == frames[2].ConvertToString())
            {
                if (true) // debug
                {
                    foreach (var item in frames)
                    {
                        Console.WriteLine(item.ConvertToString());
                    }
                }

                var multiPartMessage = new NetMQMessage(frames);
                sendSocket.SendMultipartMessage(multiPartMessage);


                //now a response should be recived on the the same socket, and I need to figure out how to handle that.

                var responseMessage = sendSocket.ReceiveMultipartMessage();
                newRouterSocket.SendMultipartMessage(responseMessage);
            }
            else
            {
                //not a valid message
                Console.WriteLine("Something bad happened in tier 2");
            }



            //lets pretend I have validated where to send this message



            Console.ReadKey();
        }