Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to respond to WebSocket Ping message? #626

Closed
otsuka opened this issue Oct 16, 2019 · 3 comments
Closed

How to respond to WebSocket Ping message? #626

otsuka opened this issue Oct 16, 2019 · 3 comments
Labels
question Question or problem question-migrate

Comments

@otsuka
Copy link

otsuka commented Oct 16, 2019

When a WebSocket Ping message (data frame) is sent to a FastAPI WebSocket server, how can I receive it and return a Pong message?

Sending Ping using aiohttp as below, it doesn't seem that FastAPI WebSocket connection receives anything.

Sending Ping
async with aiohttp.ClientSession() as sess:
    async with sess.ws_connect(WS_ENDPOINT) as ws:
        await ws.ping()
Receiving Ping
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
    await ws.accept()
    data = await ws.receive()
@otsuka otsuka added the question Question or problem label Oct 16, 2019
@euri10
Copy link
Contributor

euri10 commented Oct 29, 2019

imho the simplest is not to use FastAPI decorator but subclassing Starlette WebSocketEndpoint and sending your pong in the on_receive method

Oo that ping... 😄

@tiangolo
Copy link
Member

Ping events are defined in the WebSocket spec: https://tools.ietf.org/html/rfc6455#section-5.5.2 and are handled automatically by Uvicorn, not by FastAPI.

@otsuka
Copy link
Author

otsuka commented Feb 11, 2020

@tiangolo
Thank you for your response.
I found the code that handles a Ping message in Uvicorn.
https://github.com/encode/uvicorn/blob/master/uvicorn/protocols/websockets/wsproto_impl.py#L186-L187

@otsuka otsuka closed this as completed Feb 11, 2020
@tiangolo tiangolo changed the title [QUESTION] How to respond to WebSocket Ping message? How to respond to WebSocket Ping message? Feb 24, 2023
@tiangolo tiangolo reopened this Feb 28, 2023
@fastapi fastapi locked and limited conversation to collaborators Feb 28, 2023
@tiangolo tiangolo converted this issue into discussion #7940 Feb 28, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
question Question or problem question-migrate
Projects
None yet
Development

No branches or pull requests

3 participants