#!/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()
Create Python Multi Threaded Server Socket Program (Server.py) and Python Client Socket Program (client.py) in two separate files. Open a DOS prompt (console) and run the Server Program first. Then you will get the message "Server started" in Server side.
To use multithreading, we need to import the threading module in Python Program. A start() method is used to initiate the activity of a thread. And it calls only once for each thread so that the execution of the thread can begin.
Connect Multiple Clients in Python We have to create a brand new function and name it multi_threaded_client() ; this connects every client from the various address provided by the server simultaneously. Within the multi_threaded_client function, the connection.
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:
target
argument must be a callable
object not an "already-called" object.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With