socket 练习 sendcommand

__author__ = 'zhaobin022'


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import SocketServer
import subprocess

class MyServer(SocketServer.BaseRequestHandler):

    def handle(self):
        # print self.request,self.client_address,self.server
        conn = self.request
        conn.sendall('from %s%s ' % self.client_address )
        Flag = True
        while Flag:
            data = conn.recv(1024)
            if data == 'sendcommand':
                conn.sendall('ready')
                command = conn.recv(1024)
                p=subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                (stdoutput,erroutput) = p.communicate()
                print (stdoutput,erroutput)
                if len(erroutput) == 0:
                    total = len(stdoutput)
                    conn.sendall('total')
                    data = conn.recv(1024)
                    if data == 'ready':
                        conn.sendall(str(total))
                        data = conn.recv(1024)
                        if data == 'begin':
                            conn.sendall(stdoutput)

                else:
                    conn.sendall('error')
                    print 'send error'
                    data = conn.recv(1024)
                    if data == 'senderror':
                        print 'in senderror errouput'
                        conn.sendall(erroutput)

            elif data == 'exit':
                break




if __name__ == '__main__':
    server = SocketServer.ThreadingTCPServer(('127.0.0.1',8009),MyServer)
    server.serve_forever()

 

__author__ = 'zhaobin022'
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import socket


ip_port = ('127.0.0.1',8009)
sk = socket.socket()
sk.connect(ip_port)
sk.settimeout(5)
data = sk.recv(1024)
print 'receive:',data

while True:

    inp = raw_input('please input:')
    sk.sendall('sendcommand')
    data = sk.recv(1024)
    if data == 'ready':
        sk.sendall(inp)
    data = sk.recv(1024)
    if data == 'total':
        sk.sendall('ready')
        data = sk.recv(1024)
        print data
        total  = int(data)
        receive = 0
        sk.sendall('begin')
        while True:
            data = sk.recv(1024)
            receive += len(data)
            if total == receive:
                print data
                sk.sendall('finish')
                break
    elif data == 'error':
        print 'in error'
        sk.sendall('senderror')
        data = sk.recv(8192)
        print data
sk.close()

 

posted on 2015-12-17 09:51  zhaobin022  阅读(257)  评论(0编辑  收藏  举报