服务器端
import socket
import os
server = socket.socket()
server.bind(("localhost", 6969)) # 绑定监听端口
server.listen(5) # 监听
print("监听开始..")
while True:
conn, addr = server.accept() # 等待连接
print("conn:", conn, "\naddr:", addr) # conn连接实例
while True:
data = conn.recv(1024) # 接收
if not data: # 客户端已断开
print("客户端断开连接")
break
print("收到的命令:", data.decode("utf-8"))
res = os.popen(data.decode("utf-8")).read()
print("发送的大小:", len(res))
conn.send(str(len(res)).encode("utf-8")) # 先发送长度
confirm = conn.recv(1024) # 等待确认,解决粘包问题
print(res)
conn.send(res.encode("utf-8")) # 再发送内容
server.close()
客户端
import socket
client = socket.socket() # 生成socket连接对象
ip_port =("localhost", 6969) # 地址和端口号
client.connect(ip_port) # 连接
print("服务器已连接")
while True:
content = input(">>")
if len(content)==0: continue # 如果传入空字符会阻塞
client.send(content.encode("utf-8")) # 传送和接收都是bytes类型
receive_size = client.recv(1024) # 先接收长度,建议8192
data_size = int(receive_size.decode("utf-8"))
print("接收到的大小:", data_size)
client.send("准备好接收".encode("utf-8"))
datas = ""
while len(datas) < data_size:
data = client.recv(1024) # 多次接收内容,接收大数据
datas += data.decode("utf-8")
print(len(datas), datas) # 解码
client.close()