socket__服务端、客户端(注释版)
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/22 16:14 # @Author : Mr_zhang # @Site : # @File : server.py # @Software: PyCharm from socket import * import subprocess import struct 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() #等待客户端发送数据 ======>接收 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 = struct.pack('i',len(stdout)+len(stderr)) #根据长度制作报头 conn.send(header) #发送报头去探路 conn.send(stdout) conn.send(stderr) except Exception: break conn.close() phone.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/8/22 16:14 # @Author : Mr_zhang # @Site : # @File : client.py # @Software: PyCharm from socket import * import struct 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')) #encode之后发送出去 header_struct = phone.recv(4) #接收的报头信息 unpack_res = struct.unpack('i',header_struct) #将字节流转化为Python数据类型 total_size = unpack_res[0] #拆包之后是元组,取第一项 recv_size = 0 #接收道德数据,刚开始为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/7419081.html