client.py
· 415 B · Python
原始檔案
import zmq
# 設置 ZeroMQ 上下文
context = zmq.Context()
socket = context.socket(zmq.REQ) # 設定為請求 (REQ) 模式
socket.connect("tcp://localhost:5555") # 連接到伺服器
# 傳送請求並接收回應
for i in range(3):
message = f"客戶端 {i}"
print(f"傳送請求: {message}")
socket.send_string(message)
response = socket.recv_string()
print(f"收到回應: {response}")
| 1 | import zmq |
| 2 | |
| 3 | # 設置 ZeroMQ 上下文 |
| 4 | context = zmq.Context() |
| 5 | socket = context.socket(zmq.REQ) # 設定為請求 (REQ) 模式 |
| 6 | socket.connect("tcp://localhost:5555") # 連接到伺服器 |
| 7 | |
| 8 | # 傳送請求並接收回應 |
| 9 | for i in range(3): |
| 10 | message = f"客戶端 {i}" |
| 11 | print(f"傳送請求: {message}") |
| 12 | socket.send_string(message) |
| 13 | |
| 14 | response = socket.recv_string() |
| 15 | print(f"收到回應: {response}") |
| 16 |
server.py
· 443 B · Python
原始檔案
import zmq
# 設置 ZeroMQ 上下文
context = zmq.Context()
socket = context.socket(zmq.REP) # 設定為回應 (REP) 模式
socket.bind("tcp://*:5555") # 監聽 5555 埠口
print("伺服器啟動,等待客戶端請求...")
while True:
message = socket.recv_string() # 接收訊息
print(f"收到請求: {message}")
response = f"伺服器回應: 你好, {message}!"
socket.send_string(response) # 回應客戶端
| 1 | import zmq |
| 2 | |
| 3 | # 設置 ZeroMQ 上下文 |
| 4 | context = zmq.Context() |
| 5 | socket = context.socket(zmq.REP) # 設定為回應 (REP) 模式 |
| 6 | socket.bind("tcp://*:5555") # 監聽 5555 埠口 |
| 7 | |
| 8 | print("伺服器啟動,等待客戶端請求...") |
| 9 | |
| 10 | while True: |
| 11 | message = socket.recv_string() # 接收訊息 |
| 12 | print(f"收到請求: {message}") |
| 13 | |
| 14 | response = f"伺服器回應: 你好, {message}!" |
| 15 | socket.send_string(response) # 回應客戶端 |
| 16 |