Discuss / Python / 多线程模式下的服务器,可以用浏览器直接访问测试

多线程模式下的服务器,可以用浏览器直接访问测试

Topic source

__su_root

#1 Created at ... [Delete] [Delete and Lock User]

import os import socket import time import signal

SERVER_ADDRESS = (HOST, PORT) = '', 8888 REQUEST_QUEUE_SIZE = 5

def handle_request(client_connection): request = client_connection.recv(1024) print('Child PID: {pid}. Parent PID{ppid}'.format( pid=os.getpid(), ppid=os.getppid() )) print(request.decode('utf-8')) http_response="""\ HTTP/1.1 200 OK

Hello, World! """ client_connection.sendall(http_response.encode('utf-8')) time.sleep(3)

def grim_reaper(signum, frame): while True: try: pid, status = os.waitpid(-1, os.WNOHANG) except OSError: return

    if pid == 0:
        return

def serve_forever(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind(SERVER_ADDRESS) listen_socket.listen(REQUEST_QUEUE_SIZE) print('Serving HTTP on port {port}...'.format(port=PORT)) print('Parent PID (PPID) : {pid}\n'.format(pid=os.getpid())) signal.signal(signal.SIGCHLD, grim_reaper) while True: client_connection, client_address = listen_socket.accept() pid = os.fork() if pid == 0: listen_socket.close() handle_request(client_connection) client_connection.close() os._exit(0) else: client_connection.close()

        # print(len(clients))

if name == 'main': serve_forever()


  • 1

Reply