简单的Python服务端和客户端可以互发消息的例子
以下是一个简单的Python服务端和客户端可以互发消息的例子:
服务端代码(server.py):
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Received from client:', data.decode())
msg = input('Enter message to send to client: ')
conn.sendall(msg.encode())
客户端代码(client.py):
import socket
HOST = '127.0.0.1'
PORT = 8888
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
msg = input('Enter message to send to server: ')
s.sendall(msg.encode())
data = s.recv(1024)
print('Received from server:', data.decode())
你可以运行这两个文件,在一个终端窗口中运行服务端脚本,在另一个终端窗口中运行客户端脚本。客户端和服务端可以交替发送消息并接收消息,直到其中一个程序终止。