我一直在使用Network.WebSockets编写websocket服务器。
您可以使用如下runServer
启动 websockets 服务器:
app :: Request -> WebSockets Hybi00 ()
app _ = app1
main :: IO ()
main = runServer "0.0.0.0" 8000 app
但我真的希望 websockets 服务器与普通的 Snap 网络服务器一起耗尽端口 80。
Node.js 能够使用 Socket.io 执行此操作(请参阅左侧示例中的 http://socket.io/#how-to-use)。
这是一个 Ruby 库,可以实现类似的东西: https://github.com/simulacre/sinatra-websocket
在哈斯克尔如何做到这一点?
websockets-snap 包有一个函数:
runWebSocketsSnap :: Protocol p => (Request -> WebSockets p ()) -> Snap ()
这应该允许您从应用程序中的几乎任何地方使用 websocket。 下面是一个简单的示例:
main = quickHttpServe $ route [ ("hello", writeText "hello world")
, ("websocket", runWebSocketsSnap ...)
]
Warp 提供了用于将常规 HTTP 请求提升为 WebSockets 请求的钩子。我不知道 Snap 的首选服务器是什么...这是我用于Warp/WAI应用程序的模式:
httpApp :: Application
httpApp req = ...
wsApp :: WebSockets.Request -> WebSockets Hybi10 ()
wsApp req = do
-- check if the request should be handled
if shouldHandleRequest
then do
acceptRequest
...
else rejectRequest ...
main :: IO ()
main = do
let settings = Warp.defaultSettings
{settingsIntercept = WebSockets.intercept wsApp}
Warp.runSettings settings httpApp
return ()