ZMQ REP, knowing who send the request
Asked Answered
F

2

11

I m currently using zmq with python. Server is using REP socket.

Do I have a way, when recv a message, to know who send it ? If a receive 2 messages, I just need to know if they come from the same user or not, so an uid for example would be enough.

Fiducial answered 2/8, 2012 at 21:36 Comment(0)
S
17

It looks like you want to implement async request handling on the server side: you let the server accept requests, process them asynchronously, and send the responses back to clients whenever the response data is available for each request. Now of course: how would you know, after you're done processing a request, which client to send it back to?

With simple REP sockets, ZMQ makes sure you won't run into this kind of problem by enforcing a recv() -> send(), recv() -> send() sequentiality. In other words, after you do a recv() on a REP socket, you must do a send() before recv()ing from it again. The response will be sent back to the client you got the message from, and there's no doubt about client's address because it's only one client at a time.

But this doesn't really help when you want to parallelize the request handling, does it? There are many cases when the behavior of REP is too restrictive, and that's exactly what Multipart messages and ROUTER (or XREP) sockets are for. XREP breaks the recv() -> send() lockstep of REP, but that causes a problem as we saw earlier - how do you know which client to send the reply back to, if multiple clients are connected? In order to make this work, XREP in ZMQ adds a message part to the front of a message, like an envelope, that includes the identity of the connection that it recv()'d the request from.

There's a whole chapter in the ZMQ Guide about the advanced Request-Reply patterns. You can also find an example for handling async requests here and a good short explanation of the ZMQ connection handling here.

Seibel answered 30/10, 2012 at 10:8 Comment(0)
E
2

Reading http://zguide.zeromq.org/page%3aall#Transient-vs-Durable-Sockets, you can only get the identity of the socket you're working with... not the socket of any peers you're connected to.

This being said, just build the sender information into the message. This should be trivial to do (either with a UUID or specific name per client).

Equipment answered 3/8, 2012 at 11:41 Comment(2)
Thanks a lot for this. Yes, my message will contain the sender info (probably as an uid not sure yet). I would have prefer take the info from the socket, since letting the user give the information allows him to do session_hijack (even if this is pretty unlikely I agreee)Fiducial
well you don't 'let' them set the ID. they get their uid from you after an authentication process. This new uid changes every time they auth. This essentially eliminates almost any threat of session hijacking.Equipment

© 2022 - 2024 — McMap. All rights reserved.