zmq_server:
from datetime import datetime
import socket
server_address=('localhost',6789)
max_size=4096
print('Starting the server at',datetime.now())
print('Waiting for a client to call.')
#服务器使用socket里的两个方法进行网络链接,socket.socket,创建套接字,bind绑定IP地址和
#端口的所有数据到套接字
server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#AF_INET表示创建一个因特网套接字,SOCK_DGRAM表示我们要发送和接受数据报
server.bind(server_address)
data,client=server.recvfrom(max_size)
print('At',datetime.now(),client,'said',data)
server.sendto(b'Are you talking to me?',client)
server.close()
输出:
[1] 7023
(tf) sjj@sjj-Lenovo-V4000:~/PycharmProjects/Pub_Sub$ That voice in my head says:message #1
That voice in my head says:message #2
That voice in my head says:message #3
That voice in my head says:message #4
That voice in my head says:message #5
zmq_client:
import zmq
host='127.0.0.1'
port=6789
context=zmq.Context()
client=context.socket(zmq.REQ)
client.connect('tcp://%s:%s'%(host,port))
for num in range(1,6):
request_str='message #%s'%num
request_bytes=request_str.encode('utf-8')
client.send(request_bytes)
reply_bytes=client.recv()
reply_str=reply_bytes.decode('utf-8')
print('Sent %s,received %s'%(request_str,reply_str))
输出:
Sent message #1,received Stop saying: message #1
Sent message #2,received Stop saying: message #2
Sent message #3,received Stop saying: message #3
Sent message #4,received Stop saying: message #4
Sent message #5,received Stop saying: message #5