1、
import socket server = socket.socket() server.bind(("127.0.0.1", 8800)) server.listen(5) while True: print('server is waiting...') conn, addr = server.accept() data = conn.recv(1024) print('data:', data) # conn.send(b'hello luffycity') conn.send(b'HTTP/1.1 200 OK hello luffycity') # 添加http响应头 conn.close()
2
import socket server = socket.socket() server.bind(("127.0.0.1", 8800)) server.listen(5) while True: print('server is waiting...') conn, addr = server.accept() data = conn.recv(1024) print('data:', data) # 读取html文件 with open('index.html', 'r') as f: data = f.read() # 响应报头 + data conn.send(('HTTP/1.1 200 OK %s' % data).encode('utf8')) conn.close()
3.http请求协议
请求格式
get方式
GET / HTTP/1.1 Host: 127.0.0.1:8800 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 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
请求首行
请求头
请求头
请求头
请求头
...
post方式
login.html 登录form表单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://127.0.0.1:8800" method="post"> username: <input type="text" name="useranme"> password: <input type="password" name="password"> <input type="submit"> </form> </body> </html>
POST / HTTP/1.1 Host: 127.0.0.1:8800 Connection: keep-alive Content-Length: 26 Pragma: no-cache Cache-Control: no-cache Origin: http://127.0.0.1:8800 Upgrade-Insecure-Requests: 1 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Referer: http://127.0.0.1:8800/ Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 useranme=jack&password=2222'
请求首行 请求头 请求头 请求头 请求头 ... 请求体(a=1&b=2) # 注意只有post请求才会有请求体
区别
3、响应协议
# 响应格式 + data conn.send(('HTTP/1.1 200 OK Content-Type:text/html %s' % data).encode('utf8'))
响应码状态
4