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:
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
def __bind(self, addr):
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:
pass
while True:
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()