一个简单的WebServer,socke

2020-01-15 17:02:34 浏览数 (1)

一个简单的WebServer

代码语言:javascript复制
import socket
import threading

body = '<h1> web server </h1>'

response_params = [
    'HTTP/1.0 200 OK',
    'Content-Type: text/html;charset=utf-8',
    'Content-Length: {}rn'.format(len(body.encode())),
    body,
]

response = 'rn'.join(response_params)

def handle(conn):
    request = ''
    while 'nn' not in request and 'nrn' not in request:
        request  = conn.recv(1024).decode()
    print(request)
    conn.send(response.encode())
    conn.close()

if __name__ == '__main__':
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    address = ("127.0.0.1", 8001)
    sk.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # 端口复用
    sk.bind(address)
    sk.listen(5)
    sk.setblocking(0) # 非阻塞
    try:
        while True:
            try:
                conn,addr = sk.accept()
            except socket.error as e:
                continue
            t = threading.Thread(target=handle,args=(conn,))
            t.start()
    finally:
        sk.close()

浏览器访问显示WebServer,服务端输出request

0 人点赞