这是我的代码:
# Process connections
print('Listening on port', port)
while True:
c, addr = s.accept()
print("Got connection from", addr)
msg = "<html></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(msg.encode(encoding="utf-8")),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\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' % (response_proto, response_status, response_status_text)
c.send(r.encode(encoding="utf-8"))
c.send(response_headers_raw.encode(encoding="utf-8"))
c.send('\n'.encode(encoding="utf-8")) # to separate headers from body
c.send(msg.encode(encoding="utf-8"))
c.close()
当我在浏览器上访问我的本地 IP 时,我收到一个错误页面,上面写着
ERR_CONNECTION_RESET
我究竟做错了什么?
笔记:
完整的代码片段在这里:
import socket
# Create socket object and set protocol
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# Get name of local machine
host = socket.gethostname()
port = 80
# Bind
s.bind((host, port))
# Listen and set backlog (?)
s.listen(5)
# Process connections
print('Listening on port', port)
while True:
c, addr = s.accept()
print("Got connection from", addr)
msg = "<html></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(msg.encode(encoding="utf-8")),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\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' % (response_proto, response_status, response_status_text)
c.send(r.encode(encoding="utf-8"))
c.send(response_headers_raw.encode(encoding="utf-8"))
c.send('\n'.encode(encoding="utf-8")) # to separate headers from body
c.send(msg.encode(encoding="utf-8"))
c.close()