Last active
December 23, 2019 11:47
-
-
Save andrevdm/cc6dc7be12b805b4d82e605e54927701 to your computer and use it in GitHub Desktop.
Haskell websockets - standalone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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