服务端:
简单实例:
#服务端
import socket,os
server=socket.socket()#
server.bind(('localhost',6969))
server.listen()
conn, addr = server.accept()
print("准备接受命令", addr)
while True:
res_cmd=conn.recv(512)
data=os.popen(res_cmd.decode("utf-8")).read()
if len(data)==0:
data="书写的命令有误,请重新输入"
resv_size=len(data)
conn.send(str(resv_size).encode())#会发生粘包 解决方法是 在接收一个信息
ack=conn.recv(1024)#解决粘包的方法
print("客户端返回信息:",ack.decode('utf-8'))
conn.send(data.encode())
print("执行命令:",res_cmd.decode("utf-8"))
server.close()
#客户端
import socket
client=socket.socket()
client.connect(('218.194.176.120',6969))
while True:
msg=input(">>").strip()
client.send(msg.encode("utf-8"))
resv_size=client.recv(512)
print("返回结果大小:",resv_size)
client.send("客户端已收到文件大小信息".encode('utf-8'))
data_size=0
resv_data=''
while int(resv_size.decode())>data_size:
data = client.recv(512)
data_size+=len(data.decode())
resv_data+=data.decode()
else:
print("接收完毕....")
print(resv_data)
client.close()