Home > front end >  ZMQ : Receive from different computers
ZMQ : Receive from different computers

Time:03-08

I have different computers publishing to master computer. And I have list of their IP addresses. The code below works fine when there is only one IP in the list, but when there is more than one IP it doesn't work. when trying "Try, except" It seems that it fails when trying to connect to the second index in the ipList.

PortNum = 6666
sockets = [len( ipList )]
pollers = [len( ipList )]
context = zmq.Context()
        
for nIdx in range( 0, len( ipList ) ):
    ipAddr = ipList[nIdx]
        
    sockets[nIdx] = context.socket( zmq.SUB )
    sockets[nIdx].subscribe( '' )
            
    strTCP = 'tcp://{0}:{1}'.format( ipAddr, usePortNum )
    sockets[nIdx].connect( strTCP )
    pollers[nIdx] = zmq.Poller()
    pollers[nIdx].register(sockets[nIdx], zmq.POLLIN)

CodePudding user response:

sockets = [len( ipList )]

This doesn't create a list of length len(ipList) like you think it does. It creates a list with a single entry. So the second time through the loop you get an IndexError when you try to access the next item in the list.

Try something like this:

PortNum = 6666
sockets = []
pollers = []
context = zmq.Context()

for ipAddr in ipList:
    strTCP = f'tcp://{ipAddr}:{usePortNum}'

    socket = context.socket(zmq.SUB)
    socket.subscribe('')
    socket.connect(strTCP)

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

    sockets.append(socket)
    pollers.append(poller)
  • Related