TCPServer。handle_request()
保持与serve_forever
类似的服务请求,此后生成的所有线程均不能满足新请求,
import http.server
import socketserver
import socket
import threading
class ClientThread(threading.Thread):
def __init__(self,clientAddress,clientsocket):
threading.Thread.__init__(self)
self.csocket = clientsocket
print ("New connection added: ", clientAddress)
def run(self):
print ("Connection from : ", clientAddress)
#self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
msg = ''
while True:
data = self.csocket.recv(2048)
msg = data.decode()
if msg=='exit':
break
print ("We will be echoing back messages to the client\n", msg)
self.csocket.send(bytes(msg,'UTF-8'))
print ("Client at ", clientAddress , " disconnected...")
# local host
LOCALHOST = "127.0.0.1"
PORT = 8080
# defining our socket connection
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LOCALHOST, PORT))
Handler = http.server.SimpleHTTPRequestHandler
print("Server started at",LOCALHOST,":",PORT)
print("Waiting for client request..")
while True:
server.listen(1)
clientsock, clientAddress = server.accept()
newthread = ClientThread(clientAddress, clientsock)
newthread.start()
with socketserver.TCPServer(("", PORT), Handler) as httpd:
httpd.handle_request()
httpd.socket.close()