Skip to content

Commit

Permalink
Add example that illustrates subprotocol negotiation
Browse files Browse the repository at this point in the history
  • Loading branch information
taras committed Nov 27, 2024
1 parent ee0c11d commit 3392b9e
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions examples/subprotocol_negotiation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import asyncio
import logging
from http import HTTPStatus
from picows import ws_connect, WSTransport, WSListener, \
ws_create_server, WSUpgradeResponse, WSUpgradeResponseWithListener, \
WSUpgradeRequest

class OCPPServerClientListener(WSListener):
def on_ws_connected(self, transport: WSTransport):
print("New client connected, negotiated protocol: ", transport.response.headers["Sec-WebSocket-Protocol"])


class OCPPClientListener(WSListener):
def on_ws_connected(self, transport: WSTransport):
print("Successfully connected to the server, server supports: ",
transport.response.headers["Sec-WebSocket-Protocol"])


async def main():
def server_client_factory(request: WSUpgradeRequest):
if "ocpp2.1" in request.headers["Sec-WebSocket-Protocol"]:
return WSUpgradeResponseWithListener(WSUpgradeResponse.create_101_response(extra_headers={"Sec-WebSocket-Protocol": "ocpp2.1"}), OCPPServerClientListener())
else:
return WSUpgradeResponseWithListener(WSUpgradeResponse.create_error_response(HTTPStatus.BAD_REQUEST, b"requested websocket subprotocol is not supported"), None)

server = await ws_create_server(server_client_factory, "127.0.0.1", 27001)
asyncio.create_task(server.serve_forever())

# Client request support for either ocpp1.6 or ocpp2.1 protocol
(transport, client) = await ws_connect(OCPPClientListener, "ws://127.0.0.1:27001/", extra_headers={"Sec-WebSocket-Protocol": "ocpp1.6,ocpp2.1"})

transport.disconnect()
await transport.wait_disconnected()

server.close()
await server.wait_closed()


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
logging.getLogger("picows").setLevel(9)
asyncio.run(main())

0 comments on commit 3392b9e

Please sign in to comment.