本篇笔记学习自:What Is A Web Server?
- 网络服务器是什么鬼?
网络服务器通常指带GUI界面的主机或者超长待机的一个程序,我们这里讲的是后者。
现代服务器有很多特性,但主要还是加强网站服务器的主要功能——响应HTTP请求。
- 最简单的服务器
import socket
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind(('', 80)) # remember, 80 is the port for HTTP traffic
listen_socket.listen(1)
connection, address = listen_socket.accept()
while True:
connection.recv(1024)
connection.sendall("""HTTP/1.1 200 OK
Content-type: text/html
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>""")
connection.close()
.......
HTTP协议
请求资源指代用URI,URI有点像URL,也有点像文件系统的路径,有些服务器就是这样子对待的。
......一个从能特定路径读取文件的网络服务器
"""A web server capable of serving files from a given directory."""
import socket
import os.path
import sys
DOCUMENT_ROOT = '/tmp'
RESPONSE_TEMPLATE = """HTTP/1.1 200 OK
Content-Length: {}
{}"""
def main():
"""Main entry point for script."""
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.bind(('', int(sys.argv[1])))
listen_socket.listen(1)
while True:
connection, address = listen_socket.accept()
request = connection.recv(1024)
start_line = request.split('\n')[0]
method, uri, version = start_line.split()
path = DOCUMENT_ROOT + uri
if not os.path.exists(path):
connection.sendall('HTTP/1.1 404 Not Found\n')
else:
with open(path) as file_handle:
file_contents = file_handle.read()
response = RESPONSE_TEMPLATE.format(
len(file_contents), file_contents)
connection.sendall(response)
connection.close()
if __name__ == '__main__':
sys.exit(main())
- 还差点什么?
1.当路径不存在的时候,我们只是发送404错误,我们应该发送更详细的可以说明问题的错误说明。
2.我们没有仔细检查headers,万一客户端在headers里面说只能接收JSON格式的响应,我们这里就没有做到。
3.我们应该首先分析需要,然后将请求交给某个程序去解决。