支持多线程的socket服务,用的是ThreadingTCPServer。
代码:
from SocketServer import ThreadingTCPServer,BaseRequestHandler
import traceback
class MySocketRequestHadler(BaseRequestHandler):
"""
define by myself about handler
"""
def handle(self):
#read the data from cleint and send something to cleint
while(True):
try:
#read 1024 byte every time
data = self.request.recv(1024).strip()
#print the source
print('receive data from (%r) %r' %(self.client_address,data))
self.request.sendall(data.upper() + '\n')
except:
tranceback.print_exc()
break
if __name__ == '__main__':
host = ""
port = 8080
addr = (host,port)
#instance TCPServer
server = ThreadingTCPServer(addr,MySocketRequestHadler)
#start server
server.serve_forever()