def handle_connection(stream):
ws = WSConnection(ConnectionType.SERVER)<EOL>events = ws.events()<EOL>running = True<EOL>while running:<EOL><INDENT>in_data = stream.recv(RECEIVE_BYTES)<EOL>print('<STR_LIT>'.format(len(in_data)))<EOL>ws.receive_data(in_data)<EOL>try:<EOL><INDENT>event = next(events)<EOL><DEDENT>except StopIteration:<EOL><INDENT>print('<STR_LIT>')<EOL>return<EOL><DEDENT>if isinstance(event, Request):<EOL><INDENT>print('<STR_LIT>')<EOL>out_data = ws.send(AcceptConnection())<EOL><DEDENT>elif isinstance(event, CloseConnection):<EOL><INDENT>print('<STR_LIT>'.format(<EOL>event.code.value, event.code.name, event.reason))<EOL>out_data = ws.send(event.response())<EOL>running = False<EOL><DEDENT>elif isinstance(event, TextMessage):<EOL><INDENT>print('<STR_LIT>')<EOL>out_data = ws.send(Message(data=event.data[::-<NUM_LIT:1>]))<EOL><DEDENT>elif isinstance(event, Ping):<EOL><INDENT>print('<STR_LIT>')<EOL>out_data = ws.send(event.response())<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>'.format(event))<EOL><DEDENT>print('<STR_LIT>'.format(len(out_data)))<EOL>stream.send(out_data)<EOL><DEDENT>
Handle a connection.

The server operates a request/response cycle, so it performs a synchronous
loop:

1) Read data from network into wsproto
2) Get next wsproto event
3) Handle event
4) Send data from wsproto to network

:param stream: a socket stream