websockets-simple: Composable websockets clients

[ bsd3, library, web ] [ Propose Tags ]

See README at https://github.com/athanclark/websockets-simple#readme


[Skip to Readme]
Versions 0.0.1, 0.0.2, 0.0.2.1, 0.0.2.2, 0.0.3, 0.0.4, 0.0.4.1, 0.0.5, 0.0.6, 0.0.6.1, 0.0.6.2, 0.0.6.3, 0.0.7, 0.1.0, 0.1.1, 0.1.2, 0.1.2.1
Dependencies aeson, async, base (>=4.9 && <5), bytestring, exceptions, extractable-singleton (>=0.0.1), monad-control-aligned (>=0.0.1), profunctors, stm, transformers, vector, wai-transformers (>=0.1.0), websockets (>=0.12.4) [details]
License BSD-3-Clause
Author
Maintainer Athan Clark <athan.clark@gmail.com>
Category Web
Home page https://github.com/athanclark/websockets-simple#readme
Bug tracker https://github.com/athanclark/websockets-simple/issues
Source repo head: git clone https://github.com/athanclark/websockets-simple
Uploaded by athanclark at Thu Mar 22 18:19:20 UTC 2018
Distributions NixOS:0.1.2.1
Downloads 2470 total (83 in the last 30 days)
Rating (no votes yet) [estimated by rule of succession]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2018-03-22 [all 1 reports]
Hackage Matrix CI

Modules

[Index]

Downloads

Maintainer's Corner

For package maintainers and hackage trustees


Readme for websockets-simple-0.1.2.1

[back to package description]

websockets-simple

Provides for a slightly more composable structure for websocket apps:

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 ()
    }