Пример #1
0
        /// <summary>
        /// Send a message to broker
        /// if no message provided create a new empty one
        /// prepend the message with the MDP prologue
        /// </summary>
        /// <param name="mdpCommand">MDP command</param>
        /// <param name="data">data to be sent</param>
        /// <param name="message">the message to send</param>
        private void Send(MDPCommand mdpCommand, string data, NetMQMessage message)
        {
            // cmd, null, message      -> [REPLY],<null>,[client adr][e][reply]
            // cmd, string, null       -> [READY],[service name]
            // cmd, null, null         -> [HEARTBEAT]
            var msg = ReferenceEquals(message, null) ? new NetMQMessage() : message;

            // protocol envelope according to MDP
            // last frame is the data if available
            if (!ReferenceEquals(data, null))
            {
                // data could be multiple whitespaces or even empty(!)
                msg.Push(data);
            }
            // set MDP command                          ([client adr][e][reply] OR [service]) => [data]
            msg.Push(new[] { (byte)mdpCommand });       // [command][header][data]
            // set MDP Header
            msg.Push(m_mdpWorker);                      // [header][data]
            // set MDP empty frame as separator
            msg.Push(NetMQFrame.Empty);                 // [e][command][header][data]

            Log(string.Format("[WORKER] sending {0} to broker / Command {1}", msg, mdpCommand));

            m_worker.SendMessage(msg);
        }
Пример #2
0
        public static void Main(string[] args)
        {
            NetMQContext context = NetMQContext.Create();
            NetMQSocket  server  = context.CreateRequestSocket();

            server.Bind("tcp://*:5555");
            NetMQMessage message = new NetMQMessage();
            NetMQMessage getmass = new NetMQMessage();

            message.Append("Hallo ");
            message.Append(40);

            Client client = new Client();
            Thread t      = new Thread(new ThreadStart(client.runClient));

            t.Start();


            while (true)
            {
                server.SendMessage(message, false);
                getmass = server.ReceiveMessage(false);
                System.Console.WriteLine(getmass.Pop().ConvertToString());
                System.Console.WriteLine(getmass.Pop().ConvertToInt32());
            }
        }
        public void Send(string work)
        {
            var message = new NetMQMessage();

            message.Append(Encoding.Unicode.GetBytes(work));
            _socket.SendMessage(message);
        }
Пример #4
0
        private static void Main(string[] args)
        {
            using (var ctx = NetMQContext.Create())
            {
                using (NetMQSocket frontend = ctx.CreateRouterSocket(), backend = ctx.CreateDealerSocket())
                {
                    frontend.Bind(FRONTEND_ENDPOINT);
                    backend.Bind(BACKEND_ENDPOINT);

                    //Handler for messages coming in to the frontend
                    frontend.ReceiveReady += (sender, e) =>
                    {
                        var msg = frontend.ReceiveMessage();
                        backend.SendMessage(msg);     //Relay this message to the backend
                    };

                    //Handler for messages coming in to the backend
                    backend.ReceiveReady += (sender, e) =>
                    {
                        var msg = backend.ReceiveMessage();
                        frontend.SendMessage(msg);     //Relay this message to the frontend
                    };

                    using (var poller = new Poller())
                    {
                        poller.AddSocket(backend);
                        poller.AddSocket(frontend);

                        //Listen out for events on both sockets and raise events when messages come in
                        poller.Start();
                    }
                }
            }
        }
Пример #5
0
        public void Send(NetMQSocket socket)
        {
            NetMQMessage message = new NetMQMessage();

            message.Append(BitConverter.GetBytes(IndexStart));
            message.Append(BitConverter.GetBytes(IndexCount));
            message.Append(BitConverter.GetBytes(ByteStart));
            message.Append(BitConverter.GetBytes(ByteCount));
            socket.SendMessage(message);
        }
Пример #6
0
 private void SendMessage(NetMQSocket socket, string socketKind, Message message)
 {
     // Add metadata for the current session if needed.
     if (message.Header.Session == null)
     {
         message.Header.Session = session;
     }
     logger.LogDebug($"Sending {socketKind} message:\n\t{JsonConvert.SerializeObject(message)}");
     socket.SendMessage(context, message);
 }
Пример #7
0
        public async Task SendMessage(NetMQMessage message)
        {
            // instead of creating inproc socket which listen to messages and then send
            //to the server we just creating task and run a code on
            // the poller thread which the the thread of the clientSocket
            Task task = new Task(() => clientSocket.SendMessage(message));

            task.Start(scheduler);
            await task;

            await ReceiveMessage();
        }
        private void heartbeatTimer_Elapsed(object sender, NetMQTimerEventArgs e)
        {
            // If liveness hits zero, queue is considered disconnected
            if (--_liveness <= 0)
            {
                Console.WriteLine("{0} - W: heartbeat failure, can't reach queue.", DateTime.Now.ToLongTimeString());
                Console.WriteLine("{0} - W: reconnecting in {1} msecs...", DateTime.Now.ToLongTimeString(), _interval);

                Thread.Sleep(_interval);

                // Exponential back off
                if (_interval < INTERVAL_MAX)
                {
                    _interval *= 2;
                }

                _liveness = Paranoid.HEARTBEAT_LIVENESS;

                // Break the while loop and start the connection over
                Task.Factory.StartNew(_ =>
                {
                    Console.WriteLine("{0} - I: restart", DateTime.Now.ToLongTimeString());

                    Stop();
                    Dispose();
                    Start();
                }, _scheduler);
            }

            // Send heartbeat to queue if it's time
            if (DateTime.Now > _nextHeartbeatAt)
            {
                _nextHeartbeatAt = DateTime.Now.AddMilliseconds(Paranoid.HEARTBEAT_INTERVAL_MS);
                var heartbeatMessage = new NetMQMessage();
                heartbeatMessage.Append(new NetMQFrame(Encoding.Unicode.GetBytes(Paranoid.PPP_HEARTBEAT)));

                _worker.SendMessage(heartbeatMessage);
            }
        }
Пример #9
0
        public void runClient()
        {
            NetMQContext context = NetMQContext.Create();
            NetMQSocket  client  = context.CreateResponseSocket();

            client.Connect("tcp://localhost:5555");
            NetMQMessage message  = new NetMQMessage();
            NetMQMessage message2 = new NetMQMessage();

            while (true)
            {
                message = client.ReceiveMessage(false);
                message2.Append(message.Pop().ConvertToString() + "Tobi");
                message2.Append(message.Pop().ConvertToInt32() + 12);
                client.SendMessage(message2, false);
                System.Threading.Thread.Sleep(100);
            }
        }
Пример #10
0
        protected override void ExecutionMethod()
        {
            try
            {
                TRequest request = _requests.Take(Token);

                var envelope = new NetMQFrame(Encoding.UTF8.GetBytes(request.Topic));
                var body     = new NetMQFrame(request.ToByteArray());

                var msq = new NetMQMessage();
                msq.Append(envelope);
                msq.Append(body);

                _zmqSocket.SendMessage(msq);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #11
0
 public void Send(NetMQMessage msg)
 {
     _serverSocket.SendMessage(msg);
 }
Пример #12
0
        /// <summary>
        ///     send a request to a broker for a specific service and receive the reply
        ///
        ///     if the reply is not available within a specified time
        ///     the client deems the connection as lost and reconnects
        ///     for a specified number of times. if no reply is available
        ///     throughout this procedure the client abandons
        ///     the reply is checked for validity and returns the reply
        ///     according to the verbose flag it reports about its activities
        /// </summary>
        /// <param name="serviceName">the name of the service requested</param>
        /// <param name="request">the request message to process by service</param>
        /// <returns>the reply from service</returns>
        /// <exception cref="ApplicationException">malformed message received</exception>
        /// <exception cref="ApplicationException">malformed header received</exception>
        /// <exception cref="ApplicationException">reply received from wrong service</exception>
        public NetMQMessage Send(string serviceName, NetMQMessage request)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
            {
                throw new ApplicationException("serviceName must not be empty or null.");
            }

            if (ReferenceEquals(request, null))
            {
                throw new ApplicationException("the request must not be null");
            }
            // memorize it for the event handler
            m_serviceName = serviceName;

            // if for any reason the socket is NOT connected -> connect it!
            if (!m_connected)
            {
                Connect();
            }

            var message = new NetMQMessage(request);

            // prefix the request according to MDP specs
            // Frame 1: "MDPCxy" (six bytes MDP/Client x.y)
            // Frame 2: service name as printable string
            // Frame 3: request
            message.Push(serviceName);
            message.Push(m_mdpClient);

            Log(string.Format("[CLIENT INFO] sending {0} to service {1}", message, serviceName));

            var retiesLeft = Retries;

            while (retiesLeft > 0)
            {
                // beware of an exception if broker has not picked up the message at all
                // because one can not send multiple times! it is strict REQ -> REP -> REQ ...
                m_client.SendMessage(message);

                // Poll -> see ReceiveReady for event handling
                if (m_client.Poll(Timeout))
                {
                    // set by event handler
                    return(m_reply);
                }
                // if it failed assume communication dead and re-connect
                if (--retiesLeft > 0)
                {
                    Log("[CLIENT WARNING] no reply, reconnecting ...");

                    Connect();
                }
            }

            Log("[CLIENT ERROR] permanent error, abandoning!");

            m_client.Dispose();
            m_ctx.Dispose();

            return(null);
        }
Пример #13
0
        public void SendProcessRequest(NetMQSocket socket)
        {
            NetMQMessage msg = new NetMQMessage();

            //set file info
            msg.Append(BitConverter.GetBytes((int)ServerCodes.File));
            msg.Append(BitConverter.GetBytes(FileNames.Length));
            for (int k = 0; k < FileNames.Length; k++)
            {
                msg.Append(FileNames[k] + '\0');
            }

            if (Indexing)
            {
                msg.Append(BitConverter.GetBytes((int)ServerCodes.Index));
                msg.Append(PacketIndexFile);
                msg.Append(TimeIndexFile);
            }

            if (Filtering)
            {
                msg.Append(BitConverter.GetBytes((int)ServerCodes.Filter));
                //step 0 - gpu index
                msg.Append(BitConverter.GetBytes(GpuIndex));

                //step 1 - target memsize
                msg.Append(BitConverter.GetBytes(GpuBufferSize));

                //step 2 - streams

                msg.Append(BitConverter.GetBytes(GpuStreams));

                string filename = FileNames[0].Substring(FileNames[0].LastIndexOf('\\') + 1);
                //step 3 - capture name
                msg.Append(filename);

                //step 4 - destination folder
                msg.Append(GpfOutputFolder + '\0');

                //step 5 - constant values
                msg.Append(FilterProgram.StaticMemory.ToArray());

                //step 6 - rule program
                msg.Append(FilterProgram.RuleProgram.ToArray());
                //step 7 - filter_program
                msg.Append(FilterProgram.FilterProgram.ToArray());
                //step 8 - lookup program
                msg.Append(FilterProgram.LookupMemory.ToArray());
                //step 9 - filter names
                foreach (var filter in FilterProgram.FilterNames)
                {
                    msg.Append(filter + '\0');
                }
                //step 10 - integer names

                foreach (var integer in FilterProgram.IntegerNames)
                {
                    msg.Append(integer + '\0');
                }
            }

            msg.Append(BitConverter.GetBytes((int)ServerCodes.EndRequest));

            socket.SendMessage(msg);
        }
Пример #14
0
 public void Send(NetMQMessage msg)
 {
     _clientSocket.SendMessage(msg);
 }