一、环境要求
- Python编译环境 + 解释器
二、基本服务器代码
import socket
ADDR = '127.0.0.1'
PORT = 8888
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server.bind((ADDR, PORT))
tcp_server.listen(255)
client, addr = tcp_server.accept()
print('connected from ', addr)
raw_msg = client.recv(1024)
msg = raw_msg.decode('utf-8')
print('msg from ', addr, ': ', msg)
client.send('收到'.encode())
tcp_server.close()
三、基本客户端代码
import socket
import time
ADDR = '127.0.0.1'
PORT = 8888
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_client.connect((ADDR, PORT))
msg = '土豆土豆,我是地瓜!'
tcp_client.send(msg.encode())
time.sleep(0.5)
msg_back = tcp_client.recv(1024).decode('utf-8')
print('msg from server: ', msg_back)
tcp_client.close()
四、运行效果
- 注意:先运行服务器,再运行客户端
- 服务器:
- 客户端:
END
|