-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example that illustrates subprotocol negotiation
- Loading branch information
taras
committed
Nov 27, 2024
1 parent
ee0c11d
commit 3392b9e
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
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
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()) |