Created
August 3, 2023 10:18
-
-
Save halogenandtoast/f4f10f1e35ae6fa237a97668a156450e to your computer and use it in GitHub Desktop.
Scotty/WebSockets example
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
| 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