以下命令生成 HTTPS 连接所需的密钥:
openssl req -x509 -newkey rsa:2048 -keyout privkey.pem -out cert.pem -days 365
下面是代码,我用于在互联网上找到的项目。但我遇到了几个错误:
简单-https-server.py:
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl
httpd = HTTPServer(('localhost', 4446), BaseHTTPRequestHandler)
httpd.socket = ssl.wrap_socket (httpd.socket,
keyfile="privkey.pem",
certfile='cert.pem', server_side=True)
httpd.serve_forever()
$ python simple-https-server.py
Traceback (most recent call last):
File "/usr/lib/python3.9/ssl.py", line 1020, in _create
self.getpeername()
OSError: [Errno 128] Transport endpoint is not connected
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/cemfa/programs/html/gaming/backup/html/simple-https-server.py", line 7, in <module>
httpd.socket = ssl.wrap_socket (httpd.socket,
File "/usr/lib/python3.9/ssl.py", line 1439, in wrap_socket
return context.wrap_socket(
File "/usr/lib/python3.9/ssl.py", line 501, in wrap_socket
return self.sslsocket_class._create(
File "/usr/lib/python3.9/ssl.py", line 1032, in _create
notconn_pre_handshake_data = self.recv(1)
File "/usr/lib/python3.9/ssl.py", line 1262, in recv
return super().recv(buflen, flags)
BlockingIOError: [Errno 11] Resource temporarily unavailable
你能解释一下为什么会发生这种情况吗?
如何使用
ssl
库的问题。
尝试以下代码:
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl
server_address = ('localhost', 4446)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(certfile='cert.pem', keyfile='privkey.pem')
httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
print('Starting https server on port 4446...')
httpd.serve_forever()