Haskell Websockets库不起作用

时间:2018-08-15 01:19:06

标签: haskell websocket functional-programming

我能够成功地将websockets库与https://www.websocket.org/echo.html一起使用。我还可以通过https://www.websocket.org连接到api2.poloniex.com并成功查询websocket。

但是,当我尝试使用websockets连接到api2.poloniex.com时,出现以下错误:

Exception: MalformedResponse (ResponseHead {responseCode = 403, responseMessage = "Forbidden", responseHeaders = [("Date","Wed, 15 Aug 2018 00:27:10 GMT"),("Content-Type","text/html; charset=UTF-8"),("Transfer-Encoding","chunked"),("Connection","close"),("CF-Chl-Bypass","1"),("Set-Cookie","__cfduid=de2aa54a27d656c35f2c3b90f60cc72461534292830; expires=Thu, 15-Aug-19 00:27:10 GMT; path=/; domain=.poloniex.com; HttpOnly"),("Cache-Control","max-age=2"),("Expires","Wed, 15 Aug 2018 00:27:12 GMT"),("X-Frame-Options","SAMEORIGIN"),("Server","cloudflare"),("CF-RAY","44a788b174052eb7-MIA")]}) "Wrong response status or message."

我的代码如下:

{-# LANGUAGE OverloadedStrings #-}
module Main
    ( main
    ) where

import           Control.Concurrent  (forkIO)
import           Control.Monad       (forever, unless)
import           Control.Monad.Trans (liftIO)
import           Data.Aeson
import           Data.Text           (Text)
import qualified Data.Text           as T
import qualified Data.Text.IO        as T
import           Network.Socket      (withSocketsDo)
import qualified Network.WebSockets  as WS


--------------------------------------------------------------------------------
app :: WS.ClientApp ()
app conn = do
    putStrLn "Connected!"

    -- Fork a thread that writes WS data to stdout
    _ <- forkIO $ forever $ do
        msg <- WS.receiveData conn
        liftIO $ T.putStrLn msg

    -- Read from stdin and write to WS
    let loop = do
            line <- T.getLine
            unless (T.null line) $ WS.sendTextData conn line >> loop

    loop
    WS.sendClose conn ("Bye!" :: Text)


--------------------------------------------------------------------------------
main :: IO ()
main = withSocketsDo $ WS.runClient "api2.poloniex.com" 80 ""  app

2 个答案:

答案 0 :(得分:1)

似乎Poloniex WebSocket API需要安全连接,请参见:https://poloniex.com/support/api/(我从WS端点URL知道这一点,它使用wss://而不是ws://)。 WS.runClient使用不安全的ws://协议而不是安全的wss://协议,因此它将无法连接。尝试使用wuss库:http://hackage.haskell.org/package/wuss 并将您的主要功能重写为:

import qualified Wuss as WSS (runSecureClient)
-- ...
main :: IO ()
main = withSocketsDo $ WSS.runSecureClient "api2.poloniex.com" 443 "/" app

希望这会有所帮助!

答案 1 :(得分:1)

问题是由于我的公共IP被阻止的任何原因。我通过使用VPN解决了这个问题。