Skip to content

Instantly share code, notes, and snippets.

@halogenandtoast
Created August 3, 2023 10:18
Show Gist options
  • Select an option

  • Save halogenandtoast/f4f10f1e35ae6fa237a97668a156450e to your computer and use it in GitHub Desktop.

Select an option

Save halogenandtoast/f4f10f1e35ae6fa237a97668a156450e to your computer and use it in GitHub Desktop.
Scotty/WebSockets example
module Main (main) where
import Control.Concurrent.Async
import Control.Concurrent.Chan
import Control.Monad (forever)
import Data.Text (Text)
import Network.Wai
import Network.Wai.Handler.Warp
import Network.Wai.Handler.WebSockets
import Network.WebSockets
import Web.Scotty
newtype App = App {chan :: Chan Text}
newApp :: IO App
newApp = App <$> newChan
serverApp :: IO Application
serverApp = scottyApp $ do
get "/hello" $ do
text "hello world"
socketApp :: App -> ServerApp
socketApp app pending = do
conn <- acceptRequest pending
c <- dupChan (chan app)
race_
( forever $ do
msg <- readChan c
sendTextData conn msg
)
( forever $ do
msg <- receiveData conn
writeChan (chan app) msg
)
main :: IO ()
main = do
app <- newApp
server <- serverApp
runSettings (setPort 3000 defaultSettings) $
websocketsOr defaultConnectionOptions (socketApp app) server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment