Skip to content

Instantly share code, notes, and snippets.

@afcondon
Created February 23, 2016 17:57
Show Gist options
  • Save afcondon/1a94c84274e6cb7d7564 to your computer and use it in GitHub Desktop.
Save afcondon/1a94c84274e6cb7d7564 to your computer and use it in GitHub Desktop.
Extending the purescript-simple-websocket example
module Main where
import Prelude (Unit, return, (==), bind,($))
import Control.Monad (when)
import Control.Monad.Eff (Eff(), runPure)
import Control.Monad.Eff.Class (liftEff)
import Control.Monad.Eff.Var (($=))
import Control.Monad.Eff.Console (log, CONSOLE())
import Data.Maybe (Maybe(..))
import WebSocket (WEBSOCKET, Code(Code), Connection(Connection), Message(Message), Reason(Reason), URL(URL), runMessageEvent, runMessage, newWebSocket)
myConnect :: forall eff. String -> Eff ( ws :: WEBSOCKET, console :: CONSOLE | eff) Connection
myConnect url = do
connection@(Connection cs) <- newWebSocket (URL url) []
log "connection opened"
cs.onopen $= \event -> do
cs.send (Message "hello")
log "sent hello message"
cs.send (Message "goodbye")
log "sent goodbye message"
return connection
changeSocketConfig :: forall eff. Eff ( ws :: WEBSOCKET, console :: CONSOLE | eff) Connection -> Eff ( ws :: WEBSOCKET, console :: CONSOLE | eff) String
changeSocketConfig cs = do
Connection s <- cs
s.onmessage $= \event -> do
let received = runMessage (runMessageEvent event)
when (received == "goodbye") do
log "connection closing on receipt of goodbye note"
s.close (Just (Code 1000)) (Just (Reason "none"))
return "all's well that ends well"
main :: forall e. Eff ( ws :: WEBSOCKET, console :: CONSOLE | e) Unit
main = do
let cs = myConnect "ws://echo.websocket.org"
result <- changeSocketConfig cs
log result
log "we're done"
-- | Expected console log in the browser:
-- connection opened
-- all's well that ends well
-- we're done
-- sent hello message
-- sent goodbye message
-- connection closing on receipt of goodbye note
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment