如何在 PYZMQ 套接字中获取发件人的地址? (多个客户端,1 个服务器)

How to get address of sender in PYZMQ socket? (Multiple client, 1 server)

我创建了一个服务器,它有一个绑定到 2 个端口的套接字。现在有 2 个客户端,每个客户端连接到 1 个端口。服务器从两个客户端接收随机数,但我希望服务器知道它从哪个端口接收数据。 我知道这可能是一个非常愚蠢的问题,我对此并不陌生。请帮忙 !

服务器

    import zmq
    context = zmq.Context()
    socket = context.socket(zmq.REP)
    socket.bind("tcp://*:5555") # A single port is used for the communication

    socket.bind("tcp://*:5556") # A single port is used for the communication
    #  Wait for next request from client
    while True:

        try:
            message = socket.recv()
            msg = message.decode("utf-8") # decode the bytes to string
            print("Random Integer Received: %s" % msg) # display received string
            #  Send reply back to client
            socket.send_string("Random Integer Received from client 1")
            #sock_add = socket.getaddrinfo()
        except zmq.ZMQError as e:
            print('Unable to receive: %s', e)

客户端1(客户端2的代码相同,端口地址为5556)

    import zmq
    import time
    import numpy as np
    #import pandas as pd

    context = zmq.Context()
    num = np.random.randint(150) # Generates a random integer

    #  Socket to talk to server
    print("Connecting to server…")
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:5555")

    #  Do 100 requests, waiting each time for a response
    for request in range(100):
        k = np.random.randint(150)  # Generates a random integer
        print("Sending request %s …" % request, "sent no is %s" % k)
        socket.send_string(str(k))

        #  Get the reply.
        message = socket.recv()
        print("Received reply %s [ %s ]" % (request, message))
        time.sleep(5)  # delay of 5 seconds

请帮忙!!

我只是将您需要的信息(端口)添加到消息本身并使用 zmq.SNDMORE...

类似于:

socket.send_string("Port 5555", flags=zmq.SNDMORE)
socket.send_string(str(k)) # or 5556

然后,在服务器端,您可以根据消息本身看到消息来自哪个端口。