Reputation: 1500
I'd like to subclass the zmq.Socket class in order to automatically serialize Python objects before sending them and deserialize received messages. Now the docstring of zmq.Socket sais that in order to create a socket, I should create a context and then call
socket = context.socket(socket_type)
With this scheme, how can I use my own subclasses of zmq.Socket?
Upvotes: 0
Views: 338
Reputation: 1130
There's a (sadly undocumented) _socket_class
attribute on the zmq.Context class which can be used to customize the result of the socket(socktype)
method. For example, to add CBOR serialization methods:
import cbor
import zmq
class CBORSocket(zmq.Socket):
def send_cbor(self, obj, flags=0):
return self.send(cbor.dumps(obj), flags=flags)
def recv_cbor(self, flags=0):
return cbor.loads(self.recv(flags=flags))
class CBORContext(zmq.Context):
_socket_class = CBORSocket
def main():
ctx = CBORContext()
rep = ctx.socket(zmq.REP)
req = ctx.socket(zmq.REQ)
rep.bind('inproc://foo')
req.connect('inproc://foo')
req.send_cbor('Hello world!')
print(rep.recv_cbor())
main()
Despite the lack of documentation for _socket_class
, it does appear in one of the pyzmq example scripts although these don't appear to be used in the documentation itself. Still, I'm hoping that means it's official / unlikely to disappear arbitrarily!
Upvotes: 1
Reputation: 45
Are you aware of the send_pyobj
and recv_pyobj
methods in socket? They serialise Python objects with pickle.
Does this solve your issue? Otherwise it would be great if you could specify your question.
Upvotes: 0