如何使用 python 套接字为传入请求发送 HTTP 响应
How to send an HTTP Response for an incoming request using python sockets
我有一个 python 服务器编码以在 http://127.0.0.1:9999/ 上工作。服务器打印出传入的 http 请求。我还对响应期间要发送的内容 headers 以及内容进行了编码。这是代码:
import socket
from time import sleep
c = None #Client socket1
addr = None #Client address1
server_socket1 = socket.socket() #by default it is SOCK_STREAM (TCP) and has porotocal AF_INET (IPv4)
server_socket1.bind(('127.0.0.1',9999)) #server machine's ip and port on which it will send and recieve connections from
server_socket1.listen(2) #We will only accept two connections as of now , one for each client
print("Server started successfully!!!")
print("Waiting for connections...\n\n")
while (((c is None)and(addr is None))):
if((c is None) and (addr is None)):
c,addr = server_socket1.accept()
print("User connected to client1 socket!!")
c.send(bytes("Connected to the apps server!!!","utf-8"))
print("Client connected ip address "+str(addr))
while True:
msg = c.recv(4096)
if(msg!=None):
#print(msg)
headers, sep, body = msg.partition(b'\r\n\r\n')
headers = headers.decode('utf-8')
print(headers)
html_body = "<html><body><h1>This is a test</h1><p>More content here</p></body></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(html_body),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\r\n' % (k, v) for k, v in response_headers.items())
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK' # this can be random
# sending all this stuff
r = '%s %s %s\r\n' % (response_proto, response_status, response_status_text)
c.sendall(r.encode())
c.sendall(response_headers_raw.encode())
c.sendall(b'\r\n') # to separate headers from body
c.send(html_body.encode(encoding="utf-8"))
sleep(5)
代码没有编译错误,启动服务器并捕获我从预期的浏览器发送的请求。但是,在发送响应时,套接字连接关闭并出现错误 [WinError 10053] 已建立的连接被主机中的软件中止.
浏览器发送的请求:
终端输出:
浏览器中显示的错误:
可能导致此错误的原因是什么?之前python提示我在发送response_headers_raw变量时object必须是字节类型而不是类型'str'。因此,我使用 encode() 函数将其转换为字节类型 object,这导致我出现此错误。
任何解决方案将不胜感激!
~问候
c,addr = server_socket1.accept()
print("User connected to client1 socket!!")
c.send(bytes("Connected to the apps server!!!","utf-8"))
您在连接后立即向客户端发送“已连接到应用程序服务器!!!”。不过,客户端期待 HTTP 响应。由于它获取了您的非 HTTP 数据,因此客户端关闭了连接。稍后 c.sendall
将写入由对等方关闭的套接字,这会导致 “已建立的连接被中止”。
除此之外...
msg = c.recv(4096)
if(msg!=None):
#print(msg)
headers, sep, body = msg.partition(b'\r\n\r\n')
您的期望似乎是 c.recv
将 return None
当套接字关闭时。这不是真的,它会 return ''
代替。这意味着即使在第一个错误被修复后,如果对等方在成功读取请求并发送响应后关闭了连接,您的代码将再次 运行 进入类似的问题。
我有一个 python 服务器编码以在 http://127.0.0.1:9999/ 上工作。服务器打印出传入的 http 请求。我还对响应期间要发送的内容 headers 以及内容进行了编码。这是代码:
import socket
from time import sleep
c = None #Client socket1
addr = None #Client address1
server_socket1 = socket.socket() #by default it is SOCK_STREAM (TCP) and has porotocal AF_INET (IPv4)
server_socket1.bind(('127.0.0.1',9999)) #server machine's ip and port on which it will send and recieve connections from
server_socket1.listen(2) #We will only accept two connections as of now , one for each client
print("Server started successfully!!!")
print("Waiting for connections...\n\n")
while (((c is None)and(addr is None))):
if((c is None) and (addr is None)):
c,addr = server_socket1.accept()
print("User connected to client1 socket!!")
c.send(bytes("Connected to the apps server!!!","utf-8"))
print("Client connected ip address "+str(addr))
while True:
msg = c.recv(4096)
if(msg!=None):
#print(msg)
headers, sep, body = msg.partition(b'\r\n\r\n')
headers = headers.decode('utf-8')
print(headers)
html_body = "<html><body><h1>This is a test</h1><p>More content here</p></body></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(html_body),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\r\n' % (k, v) for k, v in response_headers.items())
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK' # this can be random
# sending all this stuff
r = '%s %s %s\r\n' % (response_proto, response_status, response_status_text)
c.sendall(r.encode())
c.sendall(response_headers_raw.encode())
c.sendall(b'\r\n') # to separate headers from body
c.send(html_body.encode(encoding="utf-8"))
sleep(5)
代码没有编译错误,启动服务器并捕获我从预期的浏览器发送的请求。但是,在发送响应时,套接字连接关闭并出现错误 [WinError 10053] 已建立的连接被主机中的软件中止.
浏览器发送的请求:
终端输出:
浏览器中显示的错误:
可能导致此错误的原因是什么?之前python提示我在发送response_headers_raw变量时object必须是字节类型而不是类型'str'。因此,我使用 encode() 函数将其转换为字节类型 object,这导致我出现此错误。
任何解决方案将不胜感激!
~问候
c,addr = server_socket1.accept()
print("User connected to client1 socket!!")
c.send(bytes("Connected to the apps server!!!","utf-8"))
您在连接后立即向客户端发送“已连接到应用程序服务器!!!”。不过,客户端期待 HTTP 响应。由于它获取了您的非 HTTP 数据,因此客户端关闭了连接。稍后 c.sendall
将写入由对等方关闭的套接字,这会导致 “已建立的连接被中止”。
除此之外...
msg = c.recv(4096)
if(msg!=None):
#print(msg)
headers, sep, body = msg.partition(b'\r\n\r\n')
您的期望似乎是 c.recv
将 return None
当套接字关闭时。这不是真的,它会 return ''
代替。这意味着即使在第一个错误被修复后,如果对等方在成功读取请求并发送响应后关闭了连接,您的代码将再次 运行 进入类似的问题。