server.py
import socket
import os
server = socket.socket()
server.bind(('localhost',8080))
server.listen()
while True:
conn,addr = server.accept()#默认堵塞,生成conn实例
print('new connect:',addr)
while True:
cmd = conn.recv(1024)#默认堵塞,如果客户端断开,将收到空数据
if not cmd:
print('the client has lost!!!')
break
else:
print('the command is ',cmd.decode())
cmd_res = os.popen(cmd.decode()).read()
if not cmd_res:
cmd_res = '无效指令'
conn.send(cmd_res.encode())
server.close()
client.py
import socket
client = socket.socket()
client.connect(('localhost',8080))
while True:
data = input('>>>').strip()
if not data:
continue
client.send(data.encode())
data = client.recv(1024)
print(data.decode())
client.close()
当服务端返回数据的大小大于客户端接受最大值,接收数据将会出现异常。可以通过客户端循环接受代码解决
client.py
import socket
client = socket.socket()
client.connect(('10.10.10.131',8080))
while True:
data = input('>>>').strip()
if not data:
continue
client.send(data.encode())
data = client.recv(1024)
data_size = int(data)
print('the size is ',data_size)
receive_size = b''
while len(receive_size) < data_size:
receive_size += client.recv(1024)
else:
print('received size is ',len(receive_size))
print(receive_size.decode())
client.close()
server.py
import socket
import os
server = socket.socket()
server.bind(('0.0.0.0',8080))
server.listen()
while True:
conn,addr = server.accept()#默认堵塞,生成conn实例
print('new connect:',addr)
while True:
cmd = conn.recv(1024)#默认堵塞,如果客户端断开,将收到空数据
if not cmd:
print('the client has lost!!!')
break
else:
print('the command is ',cmd.decode())
cmd_res = os.popen(cmd.decode()).read()
if not cmd_res:
cmd_res = '无效指令'
conn.send(str(len(cmd_res)).encode())
conn.sendall(cmd_res.encode())
server.close()