【问题标题】:Reconnect web socket [Haskell]重新连接网络套接字 [Haskell]
【发布时间】:2025-12-08 20:50:02
【问题描述】:

我正在使用wuss 库(websockets 的包装器)来创建 websocket 连接。如果网络套接字由于某种原因断开连接,如何创建循环来重新连接?

ws :: ClientApp ()
ws connection = do
    putStrLn "Connected!"

    sendTextData connection msgSubscribe -- defined elsewhere

    let loop = do 
        message <- receiveData connection
        print (message)
        loop

    loop
    sendClose connection (pack "Bye!")

main :: IO ()
main = runSecureClient "ws.kraken.com" 443 "/" ws -- retry at this point?

【问题讨论】:

    标签: haskell websocket


    【解决方案1】:

    如何“重试”取决于协议。如果你真的只是想在连接失败时从头开始重试,你可以这样做

    {-# LANGUAGE ScopedTypeVariables #-}
    import Control.Exception (catch)
    
    -- ...
    -- the rest of your code
    -- ...
    
    retryOnFailure ws = runSecureClient "ws.kraken.com" 443 "/" ws
      `catch` (\e -> 
         if e == ConnectionClosed
         then retryOnFailure ws
         else return ())
    

    但请注意,这是一个“愚蠢的”重试,因为如果远程连接意外关闭(预期关闭将导致程序结束),它实际上只是从头开始。如果您想维护任何类型的状态或类似的东西,您必须弄清楚如何为您遵循的任何协议执行此操作,但如果您只是通过一些不稳定的连接监听数据,这应该足够了。

    【讨论】: