Created
January 20, 2016 16:40
-
-
Save hdgarrood/ce6c934e47e6256e7f9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude | |
import Control.Bind ((=<<)) | |
import Control.Monad (when) | |
import Control.Monad.Eff (Eff()) | |
import Control.Monad.Eff.Var (($=), get, Var(), makeVar) | |
import Control.Monad.Eff.Console (CONSOLE(), log) | |
import Control.Monad.Eff.Console.Unsafe (logAny) | |
import Data.Maybe (Maybe(..)) | |
import DOM.Event.Types (Event(), MessageEvent(), CloseEvent()) | |
import WebSocket | |
type EffW = Eff (ws :: WEBSOCKET, console :: CONSOLE) | |
main :: EffW Unit | |
main = do | |
Connection socket <- newWebSocket (URL "ws://echo.websocket.org") [] | |
-- runConnection <<< Connection is to please the type checker | |
let socket2 = runConnection (Connection (socket { close = fakeClose })) | |
-- First try with the real connection | |
socket.onopen $= onOpen "real" (Connection socket) | |
socket.onmessage $= onMessage "real" (Connection socket) | |
socket.onclose $= onClose "real" | |
-- Now try with the "fake" one | |
socket2.onopen $= onOpen "fake" (Connection socket2) | |
socket2.onmessage $= onMessage "fake" (Connection socket2) | |
socket2.onclose $= onClose "fake" | |
onOpen :: String -> Connection -> Event -> EffW Unit | |
onOpen ty (Connection socket) event = do | |
logAny event | |
log (ty ++ ": onopen: Connection opened") | |
log <<< runURL =<< get socket.url | |
log "onopen: Sending 'hello'" | |
socket.send (Message "hello") | |
log "onopen: Sending 'goodbye'" | |
socket.send (Message "goodbye") | |
onMessage :: String -> Connection -> MessageEvent -> EffW Unit | |
onMessage ty (Connection socket) event = do | |
logAny event | |
let received = runMessage (runMessageEvent event) | |
log $ ty ++ ": onmessage: Received '" ++ received ++ "'" | |
when (received == "goodbye") do | |
log "onmessage: closing connection" | |
socket.close Nothing Nothing | |
onClose :: String -> CloseEvent -> EffW Unit | |
onClose ty event = do | |
logAny event | |
log (ty ++ ": onclose: Connection closed") | |
-- Needs a type sig because the handler effect row is separate | |
fakeClose :: forall a b eff. a -> b -> Eff (ws :: WEBSOCKET | eff) Unit | |
fakeClose _ _ = pure unit | |
runConnection :: Connection -> _ | |
runConnection (Connection s) = s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment