重点多线程
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()