Directly on the code, then explain:
#-*-Coding:utf-8-*-
# Maybe you don't want to write process-based applications for some reason, rather than write multithreaded applications
# As with previous Forkingmixin-based socket servers, socket servers written with ThreadingMixIn are subject to the same ECHO server programming pattern
# Threadedservr inherits from TCPServer and ThreadingMixIn, a new thread is created when the client connects to this multithreaded version of the server
#!usr/bin/env Python
# Python Network Programming Cookbook--chapter-1
# Optimized for Python 2.7
# It may run on any other version with/without modifications
Import OS
Import socket
Import threading
Import Socketserver
server_host= ' localhost '
Server_port=0
buf_size=1024
def client (Ip,port,message):
"" A Client Thread server test program ""
Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.connect ((Ip,port))
Try
Sock.sendall (Message)
RESPONSE=SOCK.RECV (Buf_size)
Print "Client Received:%s"%response
Finally
Sock.close ()
Class Threadedtcprequesthandler (Socketserver.baserequesthandler):
"" "Example of a thread TCP request Processing" "
def handle (self):
DATA=SELF.REQUEST.RECV (1024)
Current_thread=threading.current_thread ()
Response= "%s:%s"% (Current_thread.name,data)
Self.request.sendall (response)
Class Threadedtcpserver (Socketserver.threadingmixin,socketserver.tcpserver):
"" "There is nothing to add, inherit all the necessary" "from the parent class
Pass
If __name__== ' __main__ ':
Server=threadedtcpserver ((server_host,server_port), Threadedtcprequesthandler)
Ip,port=server.server_address
Server_thread=threading. Thread (Target=server.serve_forever)
Server_thread.daemon=true
Server_thread.start ()
Print "server loop running on thread:%s"%server_thread.name
Client (ip,port, "Hello ha from clients 1")
Client (ip,port, "Hello Handsome from 2")
Client (ip,port, "Hello Handsome from 3")
Server.shutdown ()
The three parts are composed of:
1. Client part
2. Request Processing Section:
3. Main program section:
To learn a lot about Socketserver, you can check out this blog post: http://blog.csdn.net/candcplusplus/article/details/51794411
The results of the operation are as follows:
2017.07.16 Python network programming using ThreadingMixIn in a socket server