如何使用python套接字为传入请求发送HTTP响应

2024-04-25 03:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python服务器编码来处理http://127.0.0.1:9999/。服务器打印出传入的http请求。我还对响应期间要发送的标题和内容进行了编码。代码如下:

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)

代码工作时没有编译错误,启动服务器并捕获我从浏览器发送的请求。但是,在发送响应时,套接字连接关闭并出现错误,因为主机中的软件中止了已建立的连接

从浏览器发送的请求:

enter image description here

终端中的输出:

Error while sending response to the browser

浏览器中显示的错误:

Browser window

是什么导致了这个错误?之前python提示我一个错误,即在发送response\u headers\u raw变量时,对象必须是字节类型,而不是'str'类型。因此,我使用encode()函数将其转换为字节类型的对象,这导致了这个错误

任何解决方案都将不胜感激

~z~问候


Tags: andnoneserverisresponsehtmlstatus错误
1条回答
网友
1楼 · 发布于 2024-04-25 03:35:09
    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将返回None。这不是真的,它将返回''。这意味着,即使在第一个错误修复之后,如果对等方在成功读取请求并发送响应后关闭了连接,那么您的代码也将再次遇到类似的问题

相关问题 更多 >