Earthgod
Earthgod

Reputation: 692

pyzmq poller for both recv and send messages

pyzmq poller does not work if i register it with both POLLIN and POLLOUT. The if condition could not catch the POLLIN event

server.py

import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.DEALER)
socket.bind("tcp://*:5556")


while True:
    socket.send(b"Server")

client.py

import zmq
import random
import sys
import time

port = "5556"
context = zmq.Context()
socket = context.socket(zmq.DEALER)
socket.connect("tcp://localhost:5556")


poller = zmq.Poller()
poller.register(socket, zmq.POLLIN|zmq.POLLOUT)

while True:
    socks = dict(poller.poll(50))
    if socket in socks and socks[socket] == zmq.POLLIN:
        msg = socket.recv()
        print(msg)

Upvotes: 0

Views: 495

Answers (1)

Enmanuel Verdesia
Enmanuel Verdesia

Reputation: 617

The integer values for zmq.POLLIN, zmq.POLLOUT and zmq.POLLIN | zmq.POLLOUT are 1, 2 and 3 respectively:

>>> zmq.POLLIN, zmq.POLLOUT, zmq.POLLIN | zmq.POLLOUT
(1, 2, 3)

So if in your client side the if statement is expecting receive in the socket it must await for a zmq.POLLIN (1) state, but also a zmq.POLLIN | zmq.POLLOUT (3) state, since they are exclusive.

Rewriting your if statement:

if socket in socks and socks[socket] in (zmq.POLLIN, zmq.POLLIN | zmq.POLLOUT):
    # your code    
    ...

Same way, if you want to send in the socket must await for zmq.POLLOUT (2) and zmq.POLLIN | zmq.POLLOUT (3) states.

Upvotes: 1

Related Questions