https://github.com/athanclark/websockets-simple
A simple wrapper around the websockets library.
https://github.com/athanclark/websockets-simple
algebraic-data-types api haskell websocket
Last synced: 7 months ago
JSON representation
A simple wrapper around the websockets library.
- Host: GitHub
- URL: https://github.com/athanclark/websockets-simple
- Owner: athanclark
- License: bsd-3-clause
- Created: 2017-05-06T08:26:07.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2019-10-06T19:17:58.000Z (over 6 years ago)
- Last Synced: 2024-04-25T23:02:07.900Z (about 2 years ago)
- Topics: algebraic-data-types, api, haskell, websocket
- Language: Haskell
- Size: 49.8 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# websockets-simple
Provides for a slightly more composable structure for websocket apps:
```haskell
data Input = Increment | Decrement
deriving (FromJSON)
data Output = Value Int
deriving (ToJSON)
myApp :: MonadBaseControl IO m => m (WebSocketsApp m Input Output)
myApp = do
countRef <- liftIO $ newIORef 0
emitter <- liftIO $ newIORef (Nothing :: Async ())
let killEmitter = do
mThread <- liftIO $ readIORef emitter
case mThread of
Nothing -> pure ()
Just thread -> cancel thread
pure WebSocketsApp
{ onOpen = \WebSocketsAppParams{send} ->
liftBaseWith $ \runInBase -> do
thread <- async $ forever $ do
count <- readIORef countRef
runInBase $ send $ Value count
threadDelay 1000000 -- every second, emit the current value
writeIORef emitter (Just thread)
, onReceive = \WebSocketsAppParams{send,close} x -> do
count <- liftIO $
( modifyIORef countRef $ case x of
Increment -> (+ 1)
Decrement -> (-) 1
) *> readIORef countRef
if count >= 10 || count <= -10
then close
else send (Value count)
, onClose = \mReason -> do
killEmitter
case mReason of
Nothing -> liftIO $ writeIORef countRef 0
Just _ -> pure ()
}
```