0
点赞
收藏
分享

微信扫一扫

python socket http 响应测试


http 响应测试

功能描述

访问网址 http://127.0.0.1:8000/ 显示 index.html的网页内容
访问其他网址 比如 http://127.0.0.1:8000/123 显示 404

服务器端代码

"""
httpserver v1.0
基本要求: 1. 获取来自浏览器的请求
2. 判断如果请求内容是/ 将index.html返回给客户端
3. 如果请求是其他内容则返回404
"""

"""
http 亲戚响应测试
"""

from socket import *

# http 使用 tcp传输

s = socket()
s.bind(('0.0.0.0', 8000))
s.listen(3)


def is_(c):
data = c.recv(4096).decode().split('\r\n')[0]
return data[5:].startswith(' ')


def request(c):
response = '''HTTP/1.1 200 OK
Content-Type:text/html

'''

if is_(c):
print('获取成功!')
f = open('index.html', 'rb')
for data in f:
if not data:
break
response += data.decode()
f.close()
else:
response += '''
<h1>404</h1>
'''
c.send(response.encode())


while True:
c, addr = s.accept()

request(c)

c.close()
s.close()


举报

相关推荐

0 条评论