码迷,mamicode.com
首页 > Web开发 > 详细

一个简单的WebServer,socket+threading

时间:2019-06-05 18:08:58      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:string   play   width   col   data-   一个   style   display   order   

一个简单的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

?

一个简单的WebServer,socket+threading

标签:string   play   width   col   data-   一个   style   display   order   

原文地址:https://www.cnblogs.com/sfencs-hcy/p/10980923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!