服务端:
import zmq
import sys
import time
def main():
context = zmq.Context()
skt = context.socket(zmq.PUB)
skt.bind("tcp://127.0.0.1:8888")
while True:
try:
time.sleep(3)
data = bytes('服务器时间:@' + time.strftime("%Y-%m-%d %H:%M:%S %a"), encoding='utf-8')
skt.send(data)
print('发送消息', data.decode('utf-8'))
except Exception as e:
print('异常:', e)
sys.exit()
if __name__ == '__main__':
main()
客户端:
import zmq
import sys
def main():
context = zmq.Context()
print("连接服务器...")
skt = context.socket(zmq.SUB)
skt.connect("tcp://127.0.0.1:8888")
skt.setsockopt(zmq.SUBSCRIBE, '服务器时间'.encode('utf-8')) # 只订阅 服务器时间 开头的消息
while True:
response = skt.recv().decode('utf-8')
print("接收到服务器数据: ", response)
sys.exit()
if __name__ == '__main__':
main()