python zmq客户端和服务端router socket类型

import zmq
import threading
import time

class ZMQClient(threading.Thread):
    def __init__(self):
        super(ZMQClient, self).__init__()
        self._context = zmq.Context()
        self._client_socket = self._context.socket(zmq.ROUTER)
        # 客户端标识,服务端接收数据后,知道是哪个客户端发的,多个客户端连接一个服务端
        # 时,该标识必须不一样,否则服务端只能接收其中一个发送的数据
        self._client_socket.setsockopt_string(zmq.IDENTITY, "client")

    def connnect(self, url: str):
        self._client_socket.connect(url)

    def run(self):
        while True:
            # b"server"是服务端的标识,服务端根据该标识进行过滤
            self._client_socket.send_multipart([b"server", b"Hello from client!"])
            time.sleep(1)

if __name__ == "__main__":
    client = ZMQClient()
    client.connnect("tcp://127.0.0.1:5555")
    client.start()
import zmq
import threading
import time
from zmq.error import ZMQError

class ZMQServer(threading.Thread):
    def __init__(self, addr):
        super(ZMQServer, self).__init__()
        self._context = zmq.Context()
        self._client_socket = self._context.socket(zmq.ROUTER)
        self._addr = addr

    # "tcp://localhost:5555"
    def __bind(self, addr):
        # 服务端端标识,多个客户端连接进行过滤,客户端发送时需要发送server
        # 需要再bind之前调用
        self._client_socket.setsockopt_string(zmq.IDENTITY, "server")
        self._client_socket.bind(addr)
    def run(self):
        try:
            self.__bind(self._addr)
        except ZMQError as e:
            # log error
            pass

        while True:
            # client_id客户端标识,message是实际数据,都是bytes类型
            client_id, message = self._client_socket.recv_multipart()
            print(f"recv from client  :${client_id} {message}")
            time.sleep(0.1)


if __name__ == "__main__":
    
    server = ZMQServer("tcp://*:5555")
    server.start()
   
    
    






你可能感兴趣的:(python,zmq,router)