question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unidirectional websocket connections where only the server pushes data to the clients

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

Description

Hello, Is there a way I could send data to clients over websocket without listening for when clients send data back. I’m trying to have a websocket endpoint where the server is pushing data to the client in a unidirectional way without the option for the client to send responses back. There doesn’t seem to be any code that I could find that supports this since all the documentation seems to require that the server is listening for a websocket.recieve_text(). Any help would be much appreciated, thanks.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.81.0

Python Version

3.8.13

Additional Context

No response

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
JarroVGITcommented, Sep 24, 2022

Yes, but is has nothing to do with websockets.

The issue is that the while loop is ran multiple times during a second. That’s why I sleep for 1 second, so I know the time is at least in the next second when the while loop is run again.

This is not perfect logic either, if you require data to be send exactly every second, then you would have to design for that. But that was not the issue in this topic, that is more of ansubject to be asked on SO.

1reaction
JarroVGITcommented, Sep 23, 2022

Your logic is flawed I am afraid (the modulo operation). The following works fine (and runs as-is):

import asyncio
import datetime

from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from starlette.websockets import WebSocketClose
from websockets.exceptions import ConnectionClosedError

app = FastAPI()


@app.get("/")
async def root():
    return {"hello": "world"}


@app.websocket("/wsx")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        t = datetime.datetime.utcnow().time()
        try:
            if t.second % 5 == 0:
                print("Sending the time!")
                await websocket.send_text(str(t))
                await asyncio.sleep(1)
        except ConnectionClosedError:
            print("Client disconnected.")
            break


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

Left is my client connecting with the websocket endpoint. Right is the logs of the above snippet. I disconnected using ctrl-c (otherwise it would run forever). image

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using SSE Instead Of WebSockets For Unidirectional Data ...
When it comes to data delivery from the server to the client, we are limited to two general approaches: client pull or server...
Read more >
Unidirectional Server-Client Communication using SSE in ...
In WebSocket, we have a bi-directional communication between client and server, that is both client and server get new data from each other....
Read more >
HTTP server push with WebSocket and SSE - IBM Developer
The server sends messages to the client using event stream format, a simple stream of text data that is encoded using UTF-8. Once...
Read more >
Server-sent events vs. WebSockets - LogRocket Blog
As illustrated in the diagram above, SSEs are unidirectional, so they allow sending data from the server to the client only. SSEs are...
Read more >
HTTP and Websockets: Understanding the capabilities of ...
SSE (Server Sent Events / EventSource). SSE — events can be broadcast to multiple clients (Image from javaee.ch). SSE connections can only push...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found