Open benjiqq opened 3 months ago
Hi @benjiqq Did you copy-paste this snippet from somewhere or did you write it yourself?
When you do from sanic import Websocket
like you've done, that is actually importing the Request/Response WS implementation WebSocketImpl
from here: https://github.com/sanic-org/sanic/blob/90e3bebd3b26da721c9f856d953e29b8424a027f/sanic/server/websockets/impl.py#L44
That works to act as the correct type hint for the ws
argument in your feed handler, but it is not the correct class to pass into sanic's app.run()
for protocol=Websocket
.
Normally when serving a websocket endpoint, we don't need to manually specify the WebSocketProtocol
protocol in the app runner. The default sanic HttpProtocol
will honor the HTTP Connection=upgrade
header and automatically upgrade its protocol to WebSocketProtocol
where required.
If you really do want a full WebSocket-only deployment where you have a bare websocket-only client that does not need to mess with HTTP Connection=upgrade
business, then you can set it up like this:
from sanic import Sanic, response
from sanic import Request, Websocket
from sanic.server.protocols.websocket_protocol import WebSocketProtocol
app = Sanic("webserver")
@app.websocket("/feed")
async def feed(request: Request, ws: Websocket):
while True:
data = "hello!"
print("Sending: " + data)
await ws.send(data)
data = await ws.recv()
print("Received: " + data)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, protocol=WebSocketProtocol)
Is there an existing issue for this?
Describe the bug
websockets: unexpected keyword connections
debug log
code
versions
Code snippet
No response
Expected Behavior
No response
How do you run Sanic?
As a module
Operating System
Linux
Sanic Version
23.12.1
Additional context
No response