NTchMB
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    2
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Python fastAPI實作Server sent events(SSE) 使用Python fastAPI實作Server sent events(SSE),並取代輪詢(polling)的方式來更改牌桌狀態 ### 輪詢(polling)的缺點 1. Client持續向Server發起請求,這樣不間斷的請求會加大Server的壓力,還可能因為網路延遲而影響數據的時效性 2. 主要可以透過WebSocket、Server sent events這兩種方式來解決。 ### 簡單介紹一下Server sent events 1. 基於HTTP。單向傳播(Server => Client),是WebSocket的輕量替代方案 2. 是一個長連接,因此要設定`media_type = "text/event-stream"`,返回的是字串格式 3. 需要`獨立占用一個連線`,不能跟原本的API共存同一個port ### 原本polling的方式 #### 原本Server端 - 提供一個GET的接口,給前端一直打 ```python @app.get("/games/{game_id}/player/{player_id}/status", response_model=GameStatus) async def get_status(game_id: str, player_id: str): return service.get_status(game_id, player_id) ``` #### 原本Client端 - 透過`useEffect` + `setInterval`的方式,來實作出輪詢 ```react const [gameStatus, setGameStatus] = useState<GameStatus | null>(null); useEffect(() => { // set GameStatus before the refresher triggered GetGameStatus(gameId, username).then((status: GameStatus) => { if (!isEqual(gameStatus, status)) { setGameStatus(status); } }); const intervalId = setInterval(() => { // auto-refresh GameStatus GetGameStatus(gameId, username).then((status: GameStatus) => { if (!isEqual(gameStatus, status)) { setGameStatus(status); } }); }, 1 * 1000); return () => { clearInterval(intervalId); }; }, []); ``` --- ### 後來改用SSE的方式 #### 後來Server端 - 提供一個GET的接口,讓Client進行連接,讓Server持續傳遞資料 - 返回的資料格式 1. id: 表明id 2. event: 消息的類型 3. data: 消息的資料(必須是string) 4. retry: Client重連的時間。單位是毫秒 ```python @app.get("/stream/{game_id}/player/{player_id}/status") async def message_stream(request: Request, game_id: str, player_id: str): async def event_generator(): while True: # If client closes connection, stop sending events if await request.is_disconnected(): break # Checks for new messages and return them to client if any status = service.get_status(game_id, player_id) status_str = json.dumps(status) if not status.get("final_player", None): yield { "event": "new_message", "id": "message_id", "retry": RETRY_TIMEOUT, "data": status_str, } else: yield {"event": "end", "retry": RETRY_TIMEOUT, "data": status_str} await asyncio.sleep(STREAM_DELAY) return EventSourceResponse(event_generator()) ``` #### 後來Client端 - 使用addEventListener方式來處理對應事件的處理方式 ```react let evtSource: EventSource | null = new EventSource(`${BACKEND_SSE_URL}/stream/${gameId}/player/${playerId}/status`); useEffect(() => { if (evtSource === null) { return } evtSource.addEventListener("new_message", function (event) { const data = JSON.parse(String(event.data)); if (!isEqual(gameStatus, data)) { setGameStatus(data); } }) evtSource.addEventListener("end", function(event) { console.log('Handling end....') if (evtSource === null) { return } evtSource.close(); evtSource = null; }); }, []) evtSource.onerror = () => { console.log("on error!") if (evtSource === null) { return } evtSource.close(); evtSource = null; }; ``` ### 總結 - 實作上覺得SSE的開發方式比一般的API複雜許多,需要設定連線終止的條件(`event = end 促使Client關閉連線`) - 還有資料傳給前端的資料格式也跟API不一樣,API可以傳遞json、string等等格式,SSE只能傳遞string格式,再讓前端自己轉成json ### 遇到的問題 - 在實作過程中,遇到蠻多難題的。有人對以下問題有想法的都歡迎提出討論~ 1. 為甚麼不能跟原本的API共存,當SSE與Client進行連接時,後續的API卻沒辦法接收到前端打進來的請求了 - **因為需要`獨立占用一個連線`,所以不能跟原本的API共存同一個port** 2. 當Server端意外的關閉,導致SSE連線斷開,Client端還是會一直在進行retry的動作,就算呼叫了`evtSource.close()`,F12打開卻還是會一直嘗試連接Server端 ``` GET http://127.0.0.1:8081/stream/5ca5bcfc6cc944f6aae5fd8f5d049c55/player/44444/status net::ERR_CONNECTION_REFUSED GET http://127.0.0.1:8081/stream/5ca5bcfc6cc944f6aae5fd8f5d049c55/player/44444/status net::ERR_CONNECTION_RESET ``` - **目前有嘗試在evtSource.onerror中設定close(),並把evtSource設定成null** ```react evtSource.onerror = () => { console.log("error!!!"); if (evtSource === null) { return } evtSource.close(); evtSource = null; }; ``` ### 參考資料 1. https://sairamkrish.medium.com/handling-server-send-events-with-python-fastapi-e578f3929af1 2. https://blog.csdn.net/weixin_44777680/article/details/114692497

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully