socket__服务端于客户端
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/23 15:33 # @Author : Mr_zhang # @Site : # @File : 服务端.py # @Software: PyCharm from socket import * import subprocess,struct,json phone = socket(AF_INET,SOCK_STREAM) phone.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) phone.bind(('127.0.0.1',8080)) phone.listen(7) print('startting....') #程序运行 while True: conn,client_addr = phone.accept() #等待链接,返回链接消息和客户端的IP和端口 print(conn,client_addr) #查看打印信息 print('---------->',conn,client_addr) while True: try: cmd = conn.recv(1024) if not cmd:break res = subprocess.Popen(cmd.decode('utf-8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) stdout = res.stdout.read() stderr = res.stderr.read() header_dic = {'total_size':len(stdout)+len(stderr),'filename':None,'md5':None} #制作报头 header_json = json.dumps(header_dic) #序列化报头 header_bytes = header_json.encode('utf-8') #序列化转码 conn.send(struct.pack('i',len(header_bytes))) conn.send(header_bytes) conn.send(stdout) conn.send(stderr) except Exception: break conn.close() phone.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/23 15:34 # @Author : Mr_zhang # @Site : # @File : 客户端.py # @Software: PyCharm from socket import * import struct,json phone = socket(AF_INET,SOCK_STREAM) phone.connect(('127.0.0.1',8080)) while True: cmd = input('>>>:').strip() if not cmd:continue phone.send(cmd.encode('utf-8')) #发送出去的消息需要转码 header_len = struct.unpack('i',phone.recv(4))[0] #接收到的消息解包 ([0]表示元组中的第一个值(报头)) header_bytes = phone.recv(header_len) #接收到的后续包 header_json = header_bytes.decode('utf-8') #基于上一行进行转码 header_dic = json.loads(header_json) #饭序列化 total_size = header_dic['total_size'] #反序列化之后得到的header_dic中的total_size大小 recv_size = 0 total_data = b'' while recv_size < total_size: recv_data = phone.recv(1024) recv_size+=len(recv_data) total_data+=recv_data print(total_data.decode('gbk')) phone.close()
本文来自博客园,作者:一石数字欠我15w!!!,转载请注明原文链接:https://www.cnblogs.com/52-qq/p/7419060.html