本文主要是介绍python zmq客户端和服务端router socket类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import zmq
import threading
import timeclass 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 ZMQErrorclass 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 errorpasswhile 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 socket类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!