Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Last active November 5, 2018 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenXL/cd18098738e09d55945cf89b9a23bb3d to your computer and use it in GitHub Desktop.
Save StevenXL/cd18098738e09d55945cf89b9a23bb3d to your computer and use it in GitHub Desktop.
IORef (Map UserId (TChan Text))
getConnectR :: Handler ()
getConnectR = do
mUserId <- maybeAuthId
maybe notAuthenticated connectToWebSocket mUserId
where connectToWebSocket :: UserId -> Handler ()
connectToWebSocket userId = do
webSockets (serverEventSocket userId)
return () -- return 426 (https://httpstatuses.com/426) (https://stackoverflow.com/questions/42324473/http-1-1-426-upgrade-required)
serverEventSocket :: UserId -> WebSocketsT Handler ()
serverEventSocket userId = do
wChan <- findOrCreateWChan userId
rChan <- atomically $ dupTChan wChan
forever $ atomically (readTChan rChan) >>= sendTextData
findOrCreateWChan :: UserId -> WebSocketsT Handler (TChan Text)
findOrCreateWChan userId = do
ioRefChanDir <- channels <$> getYesod
tChanDir <- readIORef ioRefChanDir
let mTChan = lookup userId tChanDir
maybe (createNewChan userId ioRefChanDir) return mTChan
createNewChan :: UserId -> IORef (Map UserId (TChan Text)) -> WebSocketsT Handler (TChan Text)
createNewChan userId ioRefChanDir = do
tChan <- newBroadcastTChanIO
atomicModifyIORef' ioRefChanDir (\dir -> (Map.insert userId tChan dir, tChan))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment