Skip to content

Instantly share code, notes, and snippets.

@madsmtm
Last active December 9, 2018 23:41
Show Gist options
  • Save madsmtm/5f3d0b9b5f68e41ff13cb5eaa15868a7 to your computer and use it in GitHub Desktop.
Save madsmtm/5f3d0b9b5f68e41ff13cb5eaa15868a7 to your computer and use it in GitHub Desktop.
`h11` example client as a class
# This file is adapted from h11's example client
# See https://github.com/python-hyper/h11/blob/master/examples/basic-client.py
import socket
import ssl
import h11
class Client:
def __init__(self, host):
self.conn = h11.Connection(our_role=h11.CLIENT)
ctx = ssl.create_default_context()
self.sock = ctx.wrap_socket(
socket.create_connection((host, 443)), server_hostname=host
)
def send(self, event):
print("Sending event:")
print(event)
print()
# Pass the event through h11's state machine and encoding machinery
data = self.conn.send(event)
# Send the resulting bytes on the wire
self.sock.sendall(data)
def next_event(self):
while True:
# Check if an event is already available
event = self.conn.next_event()
if event is h11.NEED_DATA:
# Nope, so fetch some data from the socket...
data = self.sock.recv(2048)
# ...and give it to h11 to convert back into events...
self.conn.receive_data(data)
# ...and then loop around to try again.
continue
print("Received event:")
print(event)
print()
return event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment