socket_简单报头
client---------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 14:53
# @File : client1.py
import socket
import json
ip_port = ('127.0.0.1', 8080)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
res = s.connect_ex(ip_port)
while True:
msg = input('>>: ').strip()
if len(msg) == 0: continue
if msg == 'quit': break
s.send(msg.encode('utf-8'))
response_msg_header = s.recv(100).decode("utf-8")
response_msg_header_data = json.loads(response_msg_header)
msg_size = response_msg_header_data['length']
res = s.recv(msg_size)
print("received res size ", len(res))
print(res.decode('gbk'), end='')
server-------------------------------------
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/6/6 14:53
# @File : server1.py
import socket,json
import subprocess
ip_port = ('127.0.0.1', 8080)
t_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
t_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
t_server.bind(ip_port)
t_server.listen(5)
def pack_msg_head(header, size):
bytes_head = bytes(json.dumps(header), encoding='utf-8')
fill_up_size = size - len(bytes_head)
print('need to fillup ', fill_up_size)
header['fill'] = header['fill'].zfill(fill_up_size)
print('new header ', header)
bytes_new_header = bytes(json.dumps(header), encoding='utf-8')
return bytes_new_header
while True:
conn, addr = t_server.accept()
print('客户端 ', addr)
while True:
cmd = conn.recv(1024)
if len(cmd) == 0: break
print('recv cmd ', cmd)
res = subprocess.Popen(cmd.decode('utf-8'), shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stderr = res.stderr.read()
stdout = res.stdout.read()
print('res len ', len(stdout))
msg_header = {
'length': len(stdout + stderr),
'fill': ' '
}
packed_header = pack_msg_head(msg_header, 100)
print('packed header size ', packed_header, len(packed_header))
conn.send(packed_header)
conn.send(stderr + stdout)