bburdette / websocket / WebSocket

This WebSocket Elm module lets you encode and decode messages to pass to javascript, where the actual websocket sending and receiving will take place. See the README for more.


type WebSocketCmd
    = Connect ({ name : String, address : String, protocol : String })
    | Send ({ name : String, content : String })
    | Close ({ name : String })

WebSocketCmds go from from elm out to javascript to be processed.


type WebSocketMsg
    = Error ({ name : String, error : String })
    | Data ({ name : String, data : String })

WebSocketMsgs are responses from javascript to elm after websocket operations. The name should be the same string you used in Connect.

decodeMsg : Json.Decode.Decoder WebSocketMsg

decode incoming messages from the websocket javascript.

encodeCmd : WebSocketCmd -> Json.Encode.Value

encode websocket commands into json.

receive : (Result Json.Decode.Error WebSocketMsg -> msg) -> Json.Decode.Value -> msg

make a subscription function with receive and a port, like so:

  port receiveSocketMsg : (JD.Value -> msg) -> Sub msg

  wsreceive =
      receiveSocketMsg <| WebSocket.receive WsMsg

Where WsMessage is defined in your app like this:

  type Msg
      = WsMsg (Result JD.Error WebSocket.WebSocketMsg)
      | <other message types>

then in your application subscriptions:

  subscriptions =
      \_ -> wsreceive

send : (Json.Encode.Value -> Platform.Cmd.Cmd msg) -> WebSocketCmd -> Platform.Cmd.Cmd msg

use send to make a websocket convenience function, like so:

  port sendSocketCommand : JE.Value -> Cmd msg

  wssend =
      WebSocket.send sendSocketCommand

then you can call (makes a Cmd):

  wssend <|
      WebSocket.Send
          { name = "touchpage"
          , content = dta
          }