Skip to content

Instantly share code, notes, and snippets.

@abduakhatov
Created April 8, 2023 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abduakhatov/d33016b7fe30879a0ee917309e997752 to your computer and use it in GitHub Desktop.
Save abduakhatov/d33016b7fe30879a0ee917309e997752 to your computer and use it in GitHub Desktop.
Transport protocol with SSL in asyncio
openssl genrsa -out root-ca.key 2048
openssl req -x509 -new -nodes -key root-ca.key -days 365 -out root-ca.crt
python3 ssl_web_server.py
echo "then open browser: https://localhost:4433"
Transport and Protocol with SSL
import asyncio
import ssl
def make_header():
head = b"HTTP/1.1 200 OK\r\n"
head += b"Content-Type: text/html\r\n"
head += b"\r\n"
return head
def make_body():
resp = b"<html>"
resp += b"<h1>Hello SSL</h1>"
resp += b"</html>"
return resp
sslctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
sslctx.load_cert_chain(
certfile="./root-ca.crt", keyfile="./root-ca.key"
)
class Service(asyncio.Protocol):
def connection_made(self, tr):
self.tr = tr
self.total = 0
def data_received(self, data):
if data:
resp = make_header()
resp += make_body()
self.tr.write(resp)
self.tr.close()
async def start():
server = await loop.create_server(
Service, "localhost", 4433, ssl=sslctx
)
await server.wait_closed()
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(start())
finally:
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment