#!/usr/bin/env python # -*- coding: utf-8 -*- # import socket,os,json # import sys # BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))#获取相对路径转为绝对路径赋于变量 # sys.path.append(BASE_DIR)#增加环境变量 # # from core.server_class import listen_func # s=socket.socket()#定义 # s.bind(('localhost',9000))#绑定要监听的 端口 # s.listen(5)#对列5 # print('正在监听中') # listen_func(s) import socket,struct,json,subprocess phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) phone.bind(('127.0.0.1',8090)) phone.listen(10) while True: print('starting listen 127.0.0.1:8090') conn,addr=phone.accept() print(addr) while True: print('begin receiving message') cmd=conn.recv(1024) if not cmd:break print('cmd: %s' %cmd) res=subprocess.Popen(cmd.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #错误信息 err=res.stderr.read() #打印错误信息 print(err) if err: back_msg=err else: back_msg=res.stdout.read() ##先发back_msg的长度 conn.send(struct.pack('i',len(back_msg))) ##在发真实的内容 conn.sendall(back_msg) conn.close() client #!/usr/bin/env python # -*- coding: utf-8 -*- import socket,time,struct ftp_c=socket.socket(socket.AF_INET,socket.SOCK_STREAM) res=ftp_c.connect_ex(('127.0.0.1',8090)) while True: msg=input('>>>:').strip() if len(msg) == 0:continue if msg == 'quit'or msg == 'exit':break ftp_c.send(msg.encode('utf-8')) l=ftp_c.recv(4) x=struct.unpack('i',l)[0] print(type(x),x) r_s=0 data=b'' while r_s < x: r_d=ftp_c.recv(1024) data+=r_d r_s+=len(r_d) print(data.decode('gbk'))