自己写一个web服务器(2)

2019-03-12  本文已影响0人  芒果菠萝蛋炒饭

服务器的代码

import socket

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

def handle_request(client_connection):
    request = client_connection.recv(1024)
    print(request.decode())
    http_response = b"""\
HTTP/1.1 200 OK

Hello, World!
"""
    client_connection.sendall(http_response)

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))

    while True:
        client_connection, client_address = listen_socket.accept()
        handle_request(client_connection)
        client_connection.close()

if __name__ == '__main__':
    serve_forever()

仔细看,当handle_request方法还没有结束的时候,循环会阻塞在这里,无法监听后续的请求。

客户端与服务端之间的通信

socket

Python建立socket链接

文件描述符

怎么保证你的服务器能同时处理多个请求?或者换个说法,如何编写并发服务器?

小结

上一篇下一篇

猜你喜欢

热点阅读