miguelgrinberg / simple-websocket

Simple WebSocket server and client for Python.
MIT License
78 stars 17 forks source link

Subprotocol support #17

Closed ziad-floosi closed 2 years ago

ziad-floosi commented 2 years ago

Are there any plans for subprotocol support in this library?

miguelgrinberg commented 2 years ago

I assume you are interested in support for selecting a subprotocol during handshake? That is doable, what I'm probably not going to add here is implementations for actual subprotocols.

ziad-floosi commented 2 years ago

Yeah, just selecting a subprotocol. Chrome fails to connect if the handshake reply doesn't contain the subprotocols sent in the Sec-WebSocket-Protocol header.

miguelgrinberg commented 2 years ago

Okay, I'll look into it.

miguelgrinberg commented 2 years ago

@ziad-floosi I think this should do it. To test, install simple-websocket directly from the main branch of this repository. When using Flask-Sock, you can pass the list of subprotocols accepted by the server in the SOCK_SERVER_OPTIONS dictionary (see https://flask-sock.readthedocs.io/en/latest/quickstart.html#configuration).

If the client requests a subprotocol or a list of them, the server will find the first subprotocol that it knows about and include it in the acceptance message. In the server, you can get the selected protocol inside the websocket route with ws.subprotocol.

ziad-floosi commented 2 years ago

Works perfectly, thank you so much for the quick fix. There seems to be some log message that prints out the subprotocol list when the WS server receives a request. Not super important, but just wanted to let you know.

https://github.com/miguelgrinberg/simple-websocket/blob/main/src/simple_websocket/ws.py#L339-L340

miguelgrinberg commented 2 years ago

Released as simple-websocket 0.8.0. 🎉