Skip to content

Instantly share code, notes, and snippets.

@crappygraphix
Created April 24, 2019 17:56
Show Gist options
  • Save crappygraphix/605210fce18d72c1f9682f0e34cf58b9 to your computer and use it in GitHub Desktop.
Save crappygraphix/605210fce18d72c1f9682f0e34cf58b9 to your computer and use it in GitHub Desktop.
Example of Obelisk with WebSockets
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TypeFamilies #-}
module Frontend where
import Control.Monad (join)
import Obelisk.Frontend
import Obelisk.Route
import Reflex.Dom.Core
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Common.Route
frontend :: Frontend (R FrontendRoute)
frontend = Frontend
{ _frontend_head = el "title" $ text "Ob Echo"
, _frontend_body = layout
}
layout :: ObeliskWidget js t route m => m ()
layout = do
el "strong" $
text " WebSocket Test Page"
el "p" $ do
text "Send a message to the WebSocket.org: https://www.websocket.org/echo.html"
text "'s websocket echo service:"
rec t <- inputElement $ def & inputElementConfig_setValue .~ fmap (const "") newMessage
b <- button "Send"
let newMessage = fmap ((:[]) . encodeUtf8)
$ tag (current $ value t)
$ leftmost [b, keypress Enter t]
dyDyMessages <- prerender (return $ constDyn []) $ do
ws <- webSocket "wss://echo.websocket.org" $ def & webSocketConfig_send .~ newMessage
foldDyn (\m ms -> ms ++ [m]) [] $ _webSocket_recv ws
el "p" $ text "Responses from the WebSocket.org echo service:"
_ <- el "ul"
$ simpleList (join dyDyMessages)
$ \m -> el "li" $ dynText $ fmap decodeUtf8 m
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment