Thomas
Thomas

Reputation: 12107

streaming data from events to a Suave socket

I am experimenting with Suave to send a stream of data updates; I want to replace a system we have that does polling with a socket implementation.

Here's some code:

let updateStreamSocket (webSocket : WebSocket) (context: HttpContext) =
    socket {
        printfn "connection"

        candleUpdateEvent.Publish.Add(fun d ->
            (webSocket.send Binary (d |> ByteSegment) true |> Async.RunSynchronously |> ignore)
        )

        let mutable loop = true
        while loop do
            let! msg = webSocket.read()

            match msg with
            | (Close, _, _) ->
                let emptyResponse = [||] |> ByteSegment
                do! webSocket.send Close emptyResponse true
                loop <- false

            | _ -> ()

        printfn "disconnection"
    }

Since I'm testing, I just care about the Close message, but eventually I'll have to process the Text messages to handle subscriptions.

The model is that data gets processed and each batch triggers an event (through a mailbox processor to separate threads). In the socket code, I need to handle both the socket messages I receive but also these events to send the data.

How could I join this in a single loop and wait for either event? Right now the event handler in the socket {} section will be added / removed with connection / disconnections, but it would be possible that the close get called and then an event arrives and tries to send data, etc.. while it works while testing, this is not right.

Upvotes: 1

Views: 92

Answers (0)

Related Questions