gpt4 book ai didi

python - 如何仅使用套接字库使用 Python 正确发送 HTTP 响应?

转载 作者:太空狗 更新时间:2023-10-29 21:14:49 25 4
gpt4 key购买 nike

我有一个用 Python 编写的非常简单的网络服务器。它在端口 13000 上监听,如果在浏览器中打开 http://localhost:13000,我如何让它提供一个简单的“Hello World”网页?

右边是我的代码:

# set up socket and connection
while True:
sock, addr = servSock.accept()
# WHAT GOES HERE?
sock.close()

如您所见,我不确定如何实际发回网页?

我只需要使用 socket 库。

编辑: 问题不是我不知道如何制定 HTTP 响应,而是我不知道如何让它实际显示在我的浏览器中!它只是不断旋转/加载。

最佳答案

根据问题变化更新

可能,它一直在旋转,因为结合缺少 Content-LengthConnection header ,浏览器可能会认为它是 Connection: keep-alive,因此它会永远从您的服务器接收数据。尝试发送 Connection: close,并传递实际的 Content-Length 以查看是否有帮助。


这不会达到您的预期吗? :)

#!/usr/bin/env python
# coding: utf8

import socket

MAX_PACKET = 32768

def recv_all(sock):
r'''Receive everything from `sock`, until timeout occurs, meaning sender
is exhausted, return result as string.'''

# dirty hack to simplify this stuff - you should really use zero timeout,
# deal with async socket and implement finite automata to handle incoming data

prev_timeout = sock.gettimeout()
try:
sock.settimeout(0.01)

rdata = []
while True:
try:
rdata.append(sock.recv(MAX_PACKET))
except socket.timeout:
return ''.join(rdata)

# unreachable
finally:
sock.settimeout(prev_timeout)

def normalize_line_endings(s):
r'''Convert string containing various line endings like \n, \r or \r\n,
to uniform \n.'''

return ''.join((line + '\n') for line in s.splitlines())

def run():
r'''Main loop'''

# Create TCP socket listening on 10000 port for all connections,
# with connection queue of length 1
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, \
socket.IPPROTO_TCP)
server_sock.bind(('0.0.0.0', 13000))
server_sock.listen(1)

while True:
# accept connection
client_sock, client_addr = server_sock.accept()

# headers and body are divided with \n\n (or \r\n\r\n - that's why we
# normalize endings). In real application usage, you should handle
# all variations of line endings not to screw request body
request = normalize_line_endings(recv_all(client_sock)) # hack again
request_head, request_body = request.split('\n\n', 1)

# first line is request headline, and others are headers
request_head = request_head.splitlines()
request_headline = request_head[0]
# headers have their name up to first ': '. In real world uses, they
# could duplicate, and dict drops duplicates by default, so
# be aware of this.
request_headers = dict(x.split(': ', 1) for x in request_head[1:])

# headline has form of "POST /can/i/haz/requests HTTP/1.0"
request_method, request_uri, request_proto = request_headline.split(' ', 3)

response_body = [
'<html><body><h1>Hello, world!</h1>',
'<p>This page is in location %(request_uri)r, was requested ' % locals(),
'using %(request_method)r, and with %(request_proto)r.</p>' % locals(),
'<p>Request body is %(request_body)r</p>' % locals(),
'<p>Actual set of headers received:</p>',
'<ul>',
]

for request_header_name, request_header_value in request_headers.iteritems():
response_body.append('<li><b>%r</b> == %r</li>' % (request_header_name, \
request_header_value))

response_body.append('</ul></body></html>')

response_body_raw = ''.join(response_body)

# Clearly state that connection will be closed after this response,
# and specify length of response body
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(response_body_raw),
'Connection': 'close',
}

response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in \
response_headers.iteritems())

# Reply as HTTP/1.1 server, saying "HTTP OK" (code 200).
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK' # this can be random

# sending all this stuff
client_sock.send('%s %s %s' % (response_proto, response_status, \
response_status_text))
client_sock.send(response_headers_raw)
client_sock.send('\n') # to separate headers from body
client_sock.send(response_body_raw)

# and closing connection, as we stated before
client_sock.close()

run()

更详细的描述请看description of HTTP protocol .

关于python - 如何仅使用套接字库使用 Python 正确发送 HTTP 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10114224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com