sample.hs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. {-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
  2. import Yesod.Core
  3. import Yesod.WebSockets
  4. import qualified Data.Text.Lazy as TL
  5. import Control.Monad (forever)
  6. import Control.Monad.Trans.Reader
  7. import Control.Concurrent (threadDelay)
  8. import Data.Time
  9. import Conduit
  10. data App = App
  11. instance Yesod App
  12. mkYesod "App" [parseRoutes|
  13. / HomeR GET
  14. |]
  15. timeSource :: MonadIO m => Source m TL.Text
  16. timeSource = forever $ do
  17. now <- liftIO getCurrentTime
  18. yield $ TL.pack $ show now
  19. liftIO $ threadDelay 5000000
  20. getHomeR :: Handler Html
  21. getHomeR = do
  22. webSockets $ race_
  23. (sourceWS $$ mapC TL.toUpper =$ sinkWSText)
  24. (timeSource $$ sinkWSText)
  25. defaultLayout $
  26. toWidget
  27. [julius|
  28. var conn = new WebSocket("ws://localhost:3000/");
  29. conn.onopen = function() {
  30. document.write("<p>open!</p>");
  31. document.write("<button id=button>Send another message</button>")
  32. document.getElementById("button").addEventListener("click", function(){
  33. var msg = prompt("Enter a message for the server");
  34. conn.send(msg);
  35. });
  36. conn.send("hello world");
  37. };
  38. conn.onmessage = function(e) {
  39. document.write("<p>" + e.data + "</p>");
  40. };
  41. |]
  42. main :: IO ()
  43. main = warp 3000 App