gpt4 book ai didi

websocket - 如何在suave中通过websocket实现服务器推送?

转载 作者:行者123 更新时间:2023-12-04 03:43:08 34 4
gpt4 key购买 nike

我可以写这样的东西吗

let echo (ws: WebSocket) =
fun ctx -> socket {
let loop = ref true
while !loop do
let! message = Async.Choose (ws.read()) (inbox.Receive())
match message with
| Choice1Of2 (wsMessage) ->
match wsMessage with
| Ping, _, _ -> do! ws.send Pong [||] true
| _ -> ()
| Choice2Of2 pushMessage -> do! ws.send Text pushMessage true
}

还是需要2个单独的套接字循环来进行并发读写?

最佳答案

我认为您可以使用Async.Choose解决此问题(有很多实现-尽管我不确定最规范的实现在哪里)。

也就是说,您当然可以创建两个循环-在socket { .. }中读取一个循环,以便您可以从Web套接字接收数据。写一个可以是普通的async { ... }块。

这样的事情应该可以解决问题:

let echo (ws: WebSocket) =  
// Loop that waits for the agent and writes to web socket
let notifyLoop = async {
while true do
let! msg = inbox.Receive()
do! ws.send Text msg }

// Start this using cancellation token, so that you can stop it later
let cts = new CancellationTokenSource()
Async.Start(notifyLoop, cts.Token)

// The loop that reads data from the web socket
fun ctx -> socket {
let loop = ref true
while !loop do
let! message = ws.read()
match message with
| Ping, _, _ -> do! ws.send Pong [||] true
| _ -> () }

关于websocket - 如何在suave中通过websocket实现服务器推送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33030792/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com