Last active
October 31, 2016 06:21
-
-
Save irachex/e7471d0a9b9d0e4bc0dd8a2cbc6557eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import json | |
import socket | |
import h2.connection | |
import h2.events | |
def send_response(conn, event): | |
stream_id = event.stream_id | |
response_data = json.dumps(dict(event.headers)).encode('utf-8') | |
conn.send_headers( | |
stream_id=stream_id, | |
headers=[ | |
(':status', '200'), | |
('server', 'basic-h2-server/1.0'), | |
('content-length', str(len(response_data))), | |
('content-type', 'application/json'), | |
], | |
) | |
conn.send_data( | |
stream_id=stream_id, | |
data=response_data, | |
end_stream=True | |
) | |
def handle(sock, keepalive=None): | |
if keepalive: | |
sock.settimeout(keepalive) | |
conn = h2.connection.H2Connection(client_side=False) | |
conn.initiate_connection() | |
sock.sendall(conn.data_to_send()) | |
while True: | |
try: | |
data = sock.recv(65535) | |
except socket.timeout: | |
conn.close_connection(additional_data='keepalive timeout') | |
sock.sendall(conn.data_to_send()) | |
break | |
if not data: | |
break | |
events = conn.receive_data(data) | |
for event in events: | |
print event | |
if isinstance(event, h2.events.RequestReceived): | |
send_response(conn, event) | |
data_to_send = conn.data_to_send() | |
if data_to_send: | |
sock.sendall(data_to_send) | |
port = int(sys.argv[1]) if len(sys.argv) > 1 else 5000 | |
keepalive = int(sys.argv[2]) if len(sys.argv) > 2 else None | |
sock = socket.socket() | |
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
sock.bind(('0.0.0.0', port)) | |
sock.listen(5) | |
print 'server started' | |
while True: | |
handle(sock.accept()[0], keepalive) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment