2015-10-09 6 views
9

私はこのsuaveでwebsocketでサーバープッシュを実装する方法は?

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別々のソケット・ループを必要としないようなものを書くことができますか?

答えて

2

Async.Choose(この場合は少なくとも)が適切に実装されていないため、同時読み書きのために2つの非同期ループが必要です。 this詳細を参照

9

Async.Chooseを使用してこれを解決できると思います(実装が一揃いありますが、どこが正式なものかわかりませんが)。

しかし、あなたは確かに2つのループを作成することができます - socket { .. }内の読書用の1つで、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 
      | _ ->() } 
+0

あなたはこのような場合のために良いAsync.Choose-実施を提案してください可能性:このような

何かがトリックを行う必要がありますか?ループについて:これは(https://github.com/SuaveIO/suave/issues/307#issuecomment-146873334)良いですか?感謝! –

+1

私は2ループのあなたの実装は、スレッドセーフな問題を持っていると思う(2スレッドから書き込み) –

関連する問題