private void Run() { while (_running) { NetMQMessage message; try { message = Socket.ReceiveMessage(); //_timeout } catch (Exception e) { //This needs improvement... Console.WriteLine(e); _running = false; break; } if (message.IsEmpty) { continue; } T msg = _msgReceiver(message[0].Buffer); _output.Publish(msg); } InternalDispose(); }
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(); } } } }
/// <summary> /// handle the incoming messages /// </summary> /// <remarks> /// socket strips [client adr][e] from message /// message -> [protocol header][service name][reply] /// </remarks> private void ProcessReceiveReady(object sender, NetMQSocketEventArgs e) { // a message is available within the timeout period var reply = m_client.ReceiveMessage(); Log(string.Format("[CLIENT INFO] received the reply {0}", reply)); // in production code malformed messages should be handled smarter if (reply.FrameCount < 3) { throw new ApplicationException("[CLIENT ERROR] received a malformed reply"); } var header = reply.Pop(); // [service name][reply] if (header.ConvertToString() != m_mdpClient) { throw new ApplicationException(string.Format("[CLIENT INFO] MDP Version mismatch: {0}", header)); } var service = reply.Pop(); // [reply] if (service.ConvertToString() != m_serviceName) { throw new ApplicationException(string.Format("[CLIENT INFO] answered by wrong service: {0}", service.ConvertToString())); } // now set the value for the reply of the send method! m_reply = reply; }
private void Run() { while (_running) { try { NetMQMessage msg = _replySocket.ReceiveMessage(); if (msg.IsEmpty) { continue; } if (msg.FrameCount != 3) { throw new Exception("Msg error"); } var guid = new Guid(msg[1].Buffer); if (!_requests.ContainsKey(guid)) { throw new Exception("We don't have a msg SenderId for this reply"); } TReply reply = _replyUnmarshaller(msg[2].Buffer); _fiber.Enqueue(() => Send(guid, reply)); } catch (Exception e) { _running = false; } } InternalDispose(); }
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()); } }
private void EventLoop(NetMQSocket socket) { this.logger.LogDebug("Starting shell server event loop at {Address}.", socket); while (alive) { try { // Start by pulling off the next <action>_request message // from the client. var nextMessage = socket.ReceiveMessage(context); logger.LogDebug( $"Received new message:\n" + $"\t{JsonConvert.SerializeObject(nextMessage.Header)}\n" + $"\t{JsonConvert.SerializeObject(nextMessage.ParentHeader)}\n" + $"\t{JsonConvert.SerializeObject(nextMessage.Metadata)}\n" + $"\t{JsonConvert.SerializeObject(nextMessage.Content)}" ); // If this is our first message, we need to set the session // id. if (session == null) { session = nextMessage.Header.Session; } // Get a service that can handle the message type and // dispatch. switch (nextMessage.Header.MessageType) { case "kernel_info_request": KernelInfoRequest?.Invoke(nextMessage); break; case "execute_request": ExecuteRequest?.Invoke(nextMessage); break; case "shutdown_request": ShutdownRequest?.Invoke(nextMessage); break; } } catch (ProtocolViolationException ex) { logger.LogCritical(ex, $"Protocol violation when trying to receive next ZeroMQ message."); } catch (ThreadInterruptedException) { if (alive) { continue; } else { return; } } } }
private void AsyncRead(NetMQSocket serverSocket) { while (true) { var msg = serverSocket.ReceiveMessage(); OnOnReceive(new DataEventArgs <NetMQSocket, NetMQMessage>(serverSocket, msg)); } }
private void AsyncRead(NetMQSocket socket) { OnReceiveMessage += new GWMQMessageHandler(GWMQClient_OnReceiveMessage); while (_isStart) { if (socket.HasIn) { var message = socket.ReceiveMessage(); OnReceiveMessage(socket, message); } } }
protected void AsyncRead(NetMQSocket serverSocket) { OnReceiveMessage += new GWMQMessageHandler(GWMQServer_OnReceiveMessage); while (_isStart) { if (serverSocket.HasIn) { var message = serverSocket.ReceiveMessage(); OnReceiveMessage(serverSocket, message); //Thread.Sleep(1); } } }
protected override void ExecutionMethod() { try { var msq = _zmqSocket.ReceiveMessage(); var request = SerializationMethods.FromByteArray <TRequest>(msq[1].Buffer); _action(request); } catch (Exception) { Debugger.Break(); throw; } }
/// <summary> /// upon arrival of a message process it /// and set the request variable accordingly /// </summary> /// <remarks> /// worker expects to receive either of the following /// REQUEST -> [e][header][command][client adr][e][request] /// HEARTBEAT -> [e][header][command] /// DISCONNECT -> [e][header][command] /// KILL -> [e][header][command] /// </remarks> protected virtual void ProcessReceiveReady(object sender, NetMQSocketEventArgs e) { // a request has arrived process it var request = m_worker.ReceiveMessage(); Log(string.Format("[WORKER] received {0}", request)); // make sure that we have no valid request yet! // if something goes wrong we'll return 'null' m_request = null; // any message from broker is treated as heartbeat(!) since communication exists m_liveliness = _HEARTBEAT_LIVELINESS; // check the expected message envelope and get the embedded MPD command var command = GetMDPCommand(request); // MDP command is one byte! switch (command) { case MDPCommand.Request: // the message is [client adr][e][request] // save as many addresses as there are until we hit an empty frame // - for simplicity assume it is just one m_returnIdentity = Unwrap(request); // set the class variable in order to return the request to caller m_request = request; break; case MDPCommand.Heartbeat: // reset the liveliness of the broker m_liveliness = _HEARTBEAT_LIVELINESS; break; case MDPCommand.Disconnect: // reconnect the worker Connect(); break; case MDPCommand.Kill: // stop working you worker you m_exit = true; break; default: Log("[WORKER ERROR] invalid command received!"); break; } }
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); } }
public void Issue52_ReqToRouterBug() { using (var ctx = NetMQContext.Create()) { using (NetMQSocket router = ctx.CreateRouterSocket(), req = ctx.CreateRequestSocket()) { router.Bind("inproc://example"); req.Connect("inproc://example"); string testmessage = "Simple Messaging Test"; req.Send(testmessage); var msg = router.ReceiveMessage(); Assert.AreEqual(3, msg.FrameCount); Assert.AreEqual(msg[2].ConvertToString(), testmessage); } } }
private byte[] Send(byte[] request) { try { //SendStatus result = _socket.Send(request); //if (result != SendStatus.Sent) // throw new Exception("Error sending message on socket"); NetMQMessage msg = _socket.ReceiveMessage(); //TODO:TimeSpan.FromSeconds(5) if (msg.IsEmpty) { return(new byte[0]); } return(msg[0].Buffer); } catch (Exception e) { Console.WriteLine(e); return(new byte[0]); } }
private void Run() { while (_running) { //check for time/cutoffs to trigger events... try { NetMQMessage msg = _socket.ReceiveMessage(); if (msg.IsEmpty) { continue; } ProcessRequest(msg[0].Buffer); } catch (Exception e) { _running = false; } } _socket.Dispose(); }
private void Run() { while (_running) { try { NetMQMessage message = _requestSocket.ReceiveMessage(false); if (message.IsEmpty) { continue; } byte[] id = message[0].Buffer; byte[] rid = message[1].Buffer; ProcessRequest(id, rid, message[2].Buffer); } catch (Exception e) { _running = false; } } InternalDispose(); }
public NetMQMessage ReceiveMessage() { return(_clientSocket.ReceiveMessage()); }
public void Start() { using (NetMQSocket response_socket = context.CreateResponseSocket()) using (NetMQSocket publisher_socket = context.CreateXPublisherSocket()) { string response_address = string.Format("tcp://{0}:{1}", Address, ResponsePort); string publisher_address = string.Format("tcp://{0}:{1}", Address, PublisherPort); response_socket.Bind(response_address); publisher_socket.Bind(publisher_address); Console.WriteLine("[response_socket] Bound on {0}", response_address); Console.WriteLine("[publisher_socket] Bound on {0}", publisher_address); using (Poller poller = new Poller(response_socket, publisher_socket)) { response_socket.ReceiveReady += delegate(object sender, NetMQSocketEventArgs args) { string message = response_socket.ReceiveString(); if (message.StartsWith("blow")) { string song = ""; string notes = ""; try { song = response_socket.ReceiveString(); notes = response_socket.ReceiveString(); if (song.Length > 64) { song = song.Substring(0, 64); } if (notes.Length > 64) { notes = notes.Substring(0, 64); } cache [song] = notes; Console.WriteLine("[response_socket] Received: song: {0}, notes: {1}", song, notes); } catch (Exception e) { Console.WriteLine("[response_socket] Invalid request: {0}", e.Message); } response_socket.Send("OK"); Console.WriteLine("[response_socket] Sent: OK"); publisher_socket.SendMore(song).Send(notes); Console.WriteLine("[publisher_socket] Sent: song: {0}, notes: {1}", song, notes); return; } if (message.Equals("ping")) { Console.WriteLine("[response_socket] Received: {0}", message); int timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; response_socket.Send(timestamp.ToString()); Console.WriteLine("[response_socket] Sent: {0}", timestamp); return; } Console.WriteLine("[response_socket] Invalid request: {0}", message); args.Socket.Send("Meow?"); }; // Send cached notes to new subscribers publisher_socket.ReceiveReady += delegate(object sender, NetMQSocketEventArgs args) { NetMQMessage message = publisher_socket.ReceiveMessage(); // Subscribe == 1, Unsubscibe == 0 if (message.First.Buffer [0] != 1) { return; } string song = message.First.ConvertToString().Substring(1); string cached_notes = (string)cache [song]; if (cached_notes != null) { publisher_socket.SendMore(song).Send(cached_notes); } }; poller.Start(); } } }