Vie*_* NT 9 f# websocket suave
我能写这样的东西吗?
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
}
Run Code Online (Sandbox Code Playgroud)
或者我需要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
| _ -> () }
Run Code Online (Sandbox Code Playgroud)