该程序主要实现Http服务器最原始的响应功能,运用TCP套接字,使用单进程技术,只能在某一时间内处理一个客户端的请求。
对于客户端浏览器的请求做出两种可能的处理,一种是网页存在时发送该网页给客户端,不存在时发送404请求失败警告,该程序是Http服务器的1.0版本,后续还会发实现更多功能的更高版本。
from socket import *
#处理客户请求,返回响应
def handleclient(connfd):
request = connfd.recv(4096)
requestHeadlers = request.splitlines()
for line in requestHeadlers:
print(line)
try:
f = open('index.html','r')
except IOError:
#打开文件失败,说明网页不存在,发送404
response = "HTTP/1.1 404 not found\r\n"response += '\r\n'
response += '====网页没有找到===='
else:
response = "HTTP/1.1 200 OK\r\n"
response += '\r\n'
for i in f:
response += i
finally:
f.close()
connfd.send(response.encode())
#基础配置,功能函数的调用
def main():
sockfd = socket()
sockfd.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
sockfd.bind(('0.0.0.0',8000))
sockfd.listen(10)
while True:
print('Listen to the port 8000......')
connfd,addr = sockfd.accept()
#处理请求
handleclient(connfd)
connfd.close()
if __name__ == '__main__':
main()