Skip to content

Instantly share code, notes, and snippets.

@andrevdm
Last active December 23, 2019 11:47
Show Gist options
  • Save andrevdm/cc6dc7be12b805b4d82e605e54927701 to your computer and use it in GitHub Desktop.
Save andrevdm/cc6dc7be12b805b4d82e605e54927701 to your computer and use it in GitHub Desktop.
Haskell websockets - standalone
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
import Protolude hiding (finally)
import Control.Exception.Safe (finally)
import qualified Network.WebSockets as Ws
main :: IO ()
main = do
-- Start the websocket server
Ws.runServer "127.0.0.1" 8080 $ wsApp
where
wsApp pending = do
conn <- Ws.acceptRequest pending
Ws.withPingThread conn 30 pass $ do
-- Send message on connect
Ws.sendTextData @Text conn "connected"
-- Run web socked API in an infinite loop
-- Call disconnectWs when done
flip finally disconnectWs . forever $ do
-- Get text data
msg <- Ws.receiveData @Text conn
-- Write text data
Ws.sendTextData @Text conn $ "echo: " <> msg
disconnectWs =
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment