websockets-simple: Composable websockets clients

[ bsd3, library, web ] [ Propose Tags ] [ Report a vulnerability ]

Modules

[Index] [Quick Jump]

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

  • No Candidates
Versions [RSS] 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, 0.1.3, 0.2.0
Dependencies aeson, async, base (>=4.11 && <5), bytestring, chan (>=0.0.4), exceptions, extractable-singleton (>=0.0.1), monad-control-aligned (>=0.0.1), profunctors, stm, text, transformers, 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 2019-10-06T19:18:09Z
Distributions LTSHaskell:0.2.0, Stackage:0.2.0
Reverse Dependencies 4 direct, 1 indirect [details]
Downloads 10648 total (18 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2019-10-06 [all 1 reports]

Readme for websockets-simple-0.2.0

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