# -*- coding: utf-8 -*-
"""
asyncio-server.py
~~~~~~~~~~~~~~~~~

A fully-functional HTTP/2 server using asyncio. Requires Python 3.5+.

This example demonstrates handling requests with bodies, as well as handling
those without. In particular, it demonstrates the fact that DataReceived may
be called multiple times, and that applications must handle that possibility.

Please note that this example does not handle flow control, and so only works
properly for relatively small requests. Please see other examples to understand
how flow control should work.
"""
import asyncio
import io
import json
import ssl
import collections
from typing import List, Tuple

from h2.connection import H2Connection
from h2.events import DataReceived, RequestReceived, StreamEnded
from h2.errors import ErrorCodes


RequestData = collections.namedtuple('RequestData', ['headers', 'data'])


class H2Protocol(asyncio.Protocol):
    def __init__(self):
        self.conn = H2Connection(client_side=False)
        self.transport = None
        self.stream_data = {}

    def connection_made(self, transport: asyncio.Transport):
        self.transport = transport
        self.conn.initiate_connection()
        self.transport.write(self.conn.data_to_send())

    def data_received(self, data: bytes):
        events = self.conn.receive_data(data)
        self.transport.write(self.conn.data_to_send())

        for event in events:
            if isinstance(event, RequestReceived):
                self.request_received(event.headers, event.stream_id)
            elif isinstance(event, DataReceived):
                self.receive_data(event.data, event.stream_id)
            elif isinstance(event, StreamEnded):
                self.stream_complete(event.stream_id)

            self.transport.write(self.conn.data_to_send())

    def request_received(self, headers: List[Tuple[str, str]], stream_id: int):
        headers = collections.OrderedDict(headers)
        method = headers[':method']

        # We only support GET and POST.
        if method not in ('GET', 'POST'):
            self.return_405(headers, stream_id)
            return

        # Store off the request data.
        request_data = RequestData(headers, io.BytesIO())
        self.stream_data[stream_id] = request_data

    def stream_complete(self, stream_id: int):
        """
        When a stream is complete, we can send our response.
        """
        try:
            request_data = self.stream_data[stream_id]
        except KeyError:
            # Just return, we probably 405'd this already
            return

        headers = request_data.headers
        body = request_data.data.getvalue().decode('utf-8')

        data = json.dumps(
            {"headers": headers, "body": body}, indent=4
        ).encode("utf8")

        response_headers = (
            (':status', '200'),
            ('content-type', 'application/json'),
            ('content-length', len(data)),
            ('server', 'asyncio-h2'),
        )
        self.conn.send_headers(stream_id, response_headers)
        self.conn.send_data(stream_id, data, end_stream=True)

    def return_405(self, headers: List[Tuple[str, str]], stream_id: int):
        """
        We don't support the given method, so we want to return a 405 response.
        """
        response_headers = (
            (':status', '405'),
            ('content-length', '0'),
            ('server', 'asyncio-h2'),
        )
        self.conn.send_headers(stream_id, response_headers, end_stream=True)

    def receive_data(self, data: bytes, stream_id: int):
        """
        We've received some data on a stream. If that stream is one we're
        expecting data on, save it off. Otherwise, reset the stream.
        """
        try:
            stream_data = self.stream_data[stream_id]
        except KeyError:
            self.conn.reset_stream(
                stream_id, error_code=ErrorCodes.PROTOCOL_ERROR
            )
        else:
            stream_data.data.write(data)



ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.options |= (
    ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 | ssl.OP_NO_COMPRESSION
)
ssl_context.set_ciphers("ECDHE+AESGCM")
ssl_context.load_cert_chain(certfile="cert.crt", keyfile="cert.key")
ssl_context.set_alpn_protocols(["h2"])

loop = asyncio.get_event_loop()
# Each client connection will create a new protocol instance
coro = loop.create_server(H2Protocol, '127.0.0.1', 8443, ssl=ssl_context)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

@@ -713,16 +713,44 @@
 s import
+ (%0A    ConnectionTerminated,
  DataRec
@@ -785,16 +785,18 @@
 amEnded%0A
+)%0A
 from h2.
@@ -820,16 +820,56 @@
 orCodes%0A
+from h2.exceptions import ProtocolError%0A
 %0A%0AReques
@@ -1344,16 +1344,33 @@
 bytes):%0A
+        try:%0A    
         
@@ -1407,16 +1407,55 @@
 a(data)%0A
+        except ProtocolError as e:%0A    
         
@@ -1497,25 +1497,136 @@
 _to_send())%0A
-%0A
+            self.transport.close()%0A        else:%0A            self.transport.write(self.conn.data_to_send())%0A    
         for 
@@ -1654,16 +1654,20 @@
         
+  
+  
 if isins
@@ -1689,32 +1689,36 @@
 questReceived):%0A
+    
                 
@@ -1763,32 +1763,36 @@
 vent.stream_id)%0A
+    
             elif
@@ -1837,24 +1837,28 @@
             
+    
 self.receive
@@ -1896,32 +1896,36 @@
 id)%0A            
+    
 elif isinstance(
@@ -1953,32 +1953,36 @@
                 
+ 
+   
 self.stream_comp
@@ -2003,17 +2003,126 @@
 eam_id)%0A
-%0A
+                elif isinstance(event, ConnectionTerminated):%0A                    self.transport.close()%0A%0A    
         
@@ -3294,16 +3294,20 @@
 ength', 
+str(
 len(data
@@ -3308,16 +3308,17 @@
 n(data))
+)
 ,%0A      
@@ -4371,17 +4371,16 @@
 data)%0A%0A%0A
-%0A
 ssl_cont

Update asyncio-server example to let it could be test with h2spec