socket做一个简单的web服务器处理多线程
程序员文章站
2024-03-20 16:31:04
...
重点多线程
import socket
def handle_connection(conn, addr):
import time
print("来新的客人了")
time.sleep(10)
request = ""
body = "hello"
response_params = [
"HTTP/1.0 200 OK",
"Content-Type: text/html; charset=utf-8 \r\n", # 这里一定要\r\n因为http规范 body在\r\n后面
body,
]
response = "\r\n".join(response_params)
print(conn.recv(1024))
conn.send(response.encode())
conn.close()
def main():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# serversocket.setblocking(False)
serversocket.bind(("127.0.0.1", 9001))
serversocket.listen(10)
try:
while True:
conn, address = serversocket.accept()
# 建立一个线程并且开始一个线程
import threading
t = threading.Thread(target=handle_connection, args=(conn, address))
t.start()
# handle_connection(conn, address)
finally:
serversocket.close()
if __name__ == '__main__':
main()
上一篇: 二分个人看法(供参考)
下一篇: 前后端分离 AJAX 文件下载解决方案