python之socket实现web服务器(简单) 作者:马育民 • 2019-05-26 10:03 • 阅读:10121 # 概述 本文通过socket编程实现TCP服务器,接收浏览器请求,观察浏览器发来的请求数据 ``` #encoding=utf-8 import socket,threading LEN=1024 PORT=8080 def handle(socket,addr): print('new request') buff=bytes() while True: data=socket.recv(LEN) buff+=data if b'\r\n\r\n'==buff[-4:]: break header=buff.decode('utf-8') print(header) # hearders=header.split('\r\n') # print(hearders) socket.close() def main(): server=socket.socket() server.bind(('0.0.0.0',PORT)) server.listen(128) print('启动成功,port:',PORT) while True: client,addr=server.accept() threading.Thread(target=handle,args=(client,addr)).start() if __name__ == "__main__": main() ``` 启动上面的程序,打开浏览器在地址栏输入```http://127.0.0.1:8080```发请求,接收浏览器发来的数据 如果是谷歌浏览器,发送的请求头信息如下: ``` GET / HTTP/1.1 Host: 127.0.0.1 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3676.400 QQBrowser/10.4.3505.400 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 ``` ### 说明 ``` Connection: keep-alive ``` 表示长连接,http1.1协议支持长连接 ``` Accept-Encoding: gzip, deflate, br ``` 告诉服务器可以将数据压缩 原文出处:http://malaoshi.top/show_1EF3OoqiPD2R.html