This repository has been archived on 2023-05-12. You can view files and clone it, but cannot push or open issues or pull requests.
aiosched/tests/socket_ssl.py

78 lines
2.8 KiB
Python

import aiosched
import socket as sock
import ssl
import sys
import time
_print = print
def print(*args, **kwargs):
sys.stdout.write(f"[{time.strftime('%H:%M:%S')}] ")
_print(*args, **kwargs)
async def test(host: str, port: int, bufsize: int = 4096):
socket = aiosched.socket.wrap_socket(
ssl.create_default_context().wrap_socket(
sock=sock.socket(),
# Note: do_handshake_on_connect MUST
# be set to False on the synchronous socket!
# The library handles the TLS handshake asynchronously
# and making the SSL library handle it blocks
# the entire event loop. To perform the TLS
# handshake upon connection, set this parameter
# in the AsyncSocket class instead
do_handshake_on_connect=False,
server_hostname=host,
),
)
# You have the option to do the handshake yourself
# socket.do_handshake_on_connect = False
print(f"Attempting a connection to {host}:{port}")
await socket.connect((host, port))
# await socket.do_handshake()
print("Connected")
# Ensures the code below doesn't run for more than 5 seconds
async with aiosched.skip_after(5) as scope:
# Closes the socket automatically
async with socket:
print("Entered socket context manager, sending request data")
await socket.send_all(
f"GET / HTTP/1.1\r\nUser-Agent: PostmanRuntime/7.32.2\r\nAccept: */*\r\nHost: {host}\r\nAccept-Encoding: gzip, deflate, br\r\nConnection: keep-alive\r\n\r\n".encode()
)
print("Data sent")
buffer = b""
while not buffer.endswith(b"\r\n\r\n"):
print(f"Requesting up to {bufsize} bytes (current response size: {len(buffer)})")
data = await socket.receive(bufsize)
if data:
print(f"Received {len(data)} bytes")
buffer += data
else:
print("Received empty stream, closing connection")
break
if buffer:
data = buffer.decode().split("\r\n")
print(f"HTTP Response below {'(might be incomplete)' if scope.timed_out else ''}:")
_print(f"Response: {data[0]}")
_print("Headers:")
content = False
for i, element in enumerate(data):
if i == 0:
continue
else:
if not element.strip() and not content:
sys.stdout.write("\nContent:")
content = True
if not content:
_print(f"\t{element}")
else:
for line in element.split("\n"):
_print(f"\t{line}")
_print("Done!")
aiosched.run(test, "nocturn9x.space", 443, 256, debugger=())