欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一个简单的WebServer,socket+threading

程序员文章站 2022-03-18 16:27:09
一个简单的WebServer import socket import threading body = '

web server

' response_params = [ 'HTTP/1.0 200 OK', 'Content-Type: text/html;charset=u ......

一个简单的webserver

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: {}\r\n'.format(len(body.encode())),
    body,
]

response = '\r\n'.join(response_params)

def handle(conn):
    request = ''
    while '\n\n' not in request and '\n\r\n' 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