13
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys
sys.dont_write_bytecode = True
import shlex
import subprocess
import SocketServer

sess = []

class TCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        global sess
        sess.append(self.request)
        ip,port = self.client_address
        print "#%d: client %s:%d"%(len(sess),ip,port)
        while True:
            cmd = self.request.recv(8192)
            out = subprocess.check_output(shlex.split(cmd),stderr=subprocess.STDOUT,shell=True)
            self.request.send(out)
        self.request.close()
class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass

if __name__ == "__main__":
    port = 4242
    svr = ThreadedTCPServer(("",port),TCPHandler)
    print ":%d"%port
    svr.serve_forever()

3 Answers 3

8

It is much more simple than you think:

class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass

Than you just have to use your new ThreadedTCPServer instead of TCPServer.

For more information you can read some doc.

However in your code you made some mistakes:

  1. The target argument must be a callable object not an "already-called" object.
  2. To handle many requests you need to build a Threads pool. If you only use one thread it does not make any difference if it is the main thread or a "child" thread.
Sign up to request clarification or add additional context in comments.

1 Comment

Well, thanks. The example in docs is complicated for newbie like me. So, I used your idea and now my programme works as intended.
1
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import sys
sys.dont_write_bytecode = True
import shlex
import subprocess
import SocketServer

sess = []

class TCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        global sess
        sess.append(self.request)
        ip,port = self.client_address
        print "#%d: client %s:%d"%(len(sess),ip,port)
        while True:
            cmd = self.request.recv(8192)
            out = subprocess.check_output(shlex.split(cmd),stderr=subprocess.STDOUT,shell=True)
            self.request.send(out)
        self.request.close()
class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass

if __name__ == "__main__":
    port = 4242
    svr = ThreadedTCPServer(("",port),TCPHandler)
    print ":%d"%port
    svr.serve_forever()

1 Comment

This line thread.start_new_thread(server.serve_forever(),()) should simply be server.serve_forever().
-2

Shouldn't you loop the

server = SocketServer.TCPServer(('',1520), service)
t = Thread(target=server.serve_forever())
t.start()

Just a guess..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.