Skip to content
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

Cancel awaiting event when websocket connection closed. #54

Merged
merged 2 commits into from Sep 18, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 13 additions & 16 deletions dev-server.fsx
Expand Up @@ -19,6 +19,7 @@ open Suave.Utils
open Suave.WebSocket
open System
open System.Net
open System.Threading

let port =
let rec findPort port =
Expand Down Expand Up @@ -101,39 +102,35 @@ let handleWatcherEvents, socketHandler =
| _ -> printfn "refresh event not triggered."

let socketHandler (ws: WebSocket) _ =
let mutable loop = true

let rec refreshLoop () =
async {
// TODO: how can i cancel AwaitEvent of closed websocket?
do! refreshEvent.Publish |> Async.AwaitEvent

match loop with
| true ->
printfn "refresh client."

let seg = ASCII.bytes "refreshed" |> ByteSegment
let! _ = ws.send Text seg true
printfn "refresh client."
let seg = ASCII.bytes "refreshed" |> ByteSegment
let! _ = ws.send Text seg true

return! refreshLoop ()
| false -> printfn "end refresh loop."
return! refreshLoop ()
}

let rec mainLoop () =
let rec mainLoop (ctx: CancellationTokenSource) =
socket {
let! msg = ws.read ()

match msg with
| (Close, _, _) ->
loop <- false
use _ = ctx
ctx.Cancel()

let emptyResponse = [||] |> ByteSegment
do! ws.send Close emptyResponse true
printfn "WebSocket connection closed gracefully."
| _ -> return! mainLoop ()
| _ -> return! mainLoop ctx
}

refreshLoop () |> Async.Start
mainLoop ()
let ctx = new CancellationTokenSource()
krymtkts marked this conversation as resolved.
Show resolved Hide resolved
Async.Start(refreshLoop (), ctx.Token)
mainLoop ctx


handleWatcherEvents, socketHandler
Expand Down