如何判断HTTP请求结束
如何判断HTTP请求结束
如果按下面这样写的话,在浏览器中访问12000端口,可能会显示出"Hellow World!",但浏览器实际一直处于连接状态,在edge中状态栏会显示叉号,可以手动关闭连接。
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
HTTPResponse ='HTTP/1.1 200 OK\r\n\r\n<html>Hello World!</html>'
WebSocket = socket(AF_INET, SOCK_STREAM)
WebSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
WebSocket.bind(('localhost', 12000))
WebSocket.listen(1)
HTTPSocket, addr = WebSocket.accept() # Wait Connection
while True:
print('Waiting HTTP Request...')
Request = HTTPSocket.recv(1024)
print('Send HTTP Response!')
HTTPSocket.sendall(HTTPResponse.encode('utf-8')) # Send
可以使用的方法有:
- Content-Length 指明了请求体的长度,可以直接读取指定长度的数据
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
HTTPResponse ='HTTP/1.1 200 OK\r\nContent-Length: 25\r\n\r\n<html>Hello World!</html>'
WebSocket = socket(AF_INET, SOCK_STREAM)
WebSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
WebSocket.bind(('localhost', 12000))
WebSocket.listen(1)
HTTPSocket, addr = WebSocket.accept()
while True:
print('Waiting HTTP Request...')
Request = HTTPSocket.recv(1024)
print('Send HTTP Response!')
HTTPSocket.send(HTTPResponse.encode('utf-8'))
- Transfer-Encoding: chunked 数据要求为分块传输,格式为n\r\n数据\r\n,n为数据长度,n为0表示结束
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
HTTPResponse = 'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n'
WebSocket = socket(AF_INET, SOCK_STREAM)
WebSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
WebSocket.bind(('localhost', 12000))
WebSocket.listen(1)
HTTPSocket, addr = WebSocket.accept()
while True:
print('Waiting HTTP Request...')
Request = HTTPSocket.recv(1024)
print('Send HTTP Response!')
HTTPSocket.send(HTTPResponse.encode('utf-8'))
HTTPSocket.send('5\r\nHello\r\n'.encode('utf-8'))
HTTPSocket.send('0\r\n\r\n'.encode('utf-8'))
- Connection: close 请求结束后关闭连接
from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
HTTPResponse ='HTTP/1.1 200 OK\r\n\r\n<html>Hello World!</html>'
WebSocket = socket(AF_INET, SOCK_STREAM)
WebSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
WebSocket.bind(('localhost', 12000))
WebSocket.listen(1)
while True:
print('Waiting HTTP Request...')
HTTPSocket, addr = WebSocket.accept()
Request = HTTPSocket.recv(1024)
print('Send HTTP Response!')
HTTPSocket.send(HTTPResponse.encode('utf-8'))
HTTPSocket.close()