from socketserver import StreamRequestHandler
from socketserver import TCPServer
import gevent
from gevent import monkey
from time import ctime
monkey.patch_all()
HOST = ''
PORT = 8888
ADDR = (HOST, PORT)
class GeventServer(TCPServer):
def _handle_request_noblock(self):
"""Handle one request, without blocking.
I assume that selector.select() has returned that the socket is
readable before this function was called, so there should be no risk of
blocking in get_request().
"""
try:
request, client_address = self.get_request()
except OSError:
return
if self.verify_request(request, client_address):
try:
gevent.spawn(self.process_request, request, client_address)
except Exception:
self.handle_error(request, client_address)
self.shutdown_request(request)
except:
self.shutdown_request(request)
raise
else:
self.shutdown_request(request)
class MyRequestHandler(StreamRequestHandler):
def handle(self):
self.wfile.write('hello world\r\n'.encode())
print('...connected from:', self.client_address)
content = self.rfile.read()
print(content)
message = '[%s] %s' % (ctime(), content.decode())
self.request.sendall(msg)
print(self.request)
tcpSev = GeventServer(ADDR, MyRequestHandler)
tcpSev.serve_forever()
网友评论