参考来源:https://blog.csdn.net/qq_40828914/article/details/120895412
# 用socket实现一个简单的服务器,可以通过浏览器来访问标签:__,网页,socket,python,nSec,time,data,conn From: https://www.cnblogs.com/lld76/p/16827110.html
import socket,time
def handle(conn): # 请求处理函数
data = conn.recv(1024)
print('data', data)
print('result', data.decode().split(' '))
conn.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8"))
data = "<h1>hello taobao<h1><br><h2>time:{{time}}</h2>"
conn.send(bytes(data,encoding="utf-8"))
now_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
html = data.replace("{{time}}", now_time)
conn.send(bytes(html, encoding="utf-8"))
def main():
server = socket.socket()
server.bind(("localhost", 8000))
server.listen(5)
print("服务启动")
while True:
conn, addr = server.accept()
print(conn, addr)
handle(conn)
conn.close()
if __name__ == "__main__":
main()
'''
data b'
GET / HTTP/1.1\r\n
Host: localhost:8000\r\n
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"\r\n
sec-ch-ua-mobile: ?0\r\n
sec-ch-ua-platform: "Windows"\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\r\n
Sec-Fetch-Site: cross-site\r\n
Sec-Fetch-Mode: navigate\r\n
Sec-Fetch-User: ?1\r\n
Sec-Fetch-Dest: document\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n\r\n'
'''