Web Sockets


Clone the code or follow along in the online editor.


We are going to make a simple chat app. There will be a text field so you can type things in and a region that shows all the messages we have received so far. Web sockets are great for this scenario because they let us set up a persistent connection with the server. This means:

  1. You can send messages cheaply whenever you want.
  2. The server can send you messages whenever it feels like it.

In other words, WebSocket is one of the rare libraries that makes use of both commands and subscriptions.

This program happens to be pretty short, so here is the full thing:

  1. import Html exposing (..)
  2. import Html.Attributes exposing (..)
  3. import Html.Events exposing (..)
  4. import WebSocket
  5. main =
  6. Html.program
  7. { init = init
  8. , view = view
  9. , update = update
  10. , subscriptions = subscriptions
  11. }
  12. -- MODEL
  13. type alias Model =
  14. { input : String
  15. , messages : List String
  16. }
  17. init : (Model, Cmd Msg)
  18. init =
  19. (Model "" [], Cmd.none)
  20. -- UPDATE
  21. type Msg
  22. = Input String
  23. | Send
  24. | NewMessage String
  25. update : Msg -> Model -> (Model, Cmd Msg)
  26. update msg {input, messages} =
  27. case msg of
  28. Input newInput ->
  29. (Model newInput messages, Cmd.none)
  30. Send ->
  31. (Model "" messages, WebSocket.send "ws://echo.websocket.org" input)
  32. NewMessage str ->
  33. (Model input (str :: messages), Cmd.none)
  34. -- SUBSCRIPTIONS
  35. subscriptions : Model -> Sub Msg
  36. subscriptions model =
  37. WebSocket.listen "ws://echo.websocket.org" NewMessage
  38. -- VIEW
  39. view : Model -> Html Msg
  40. view model =
  41. div []
  42. [ div [] (List.map viewMessage model.messages)
  43. , input [onInput Input] []
  44. , button [onClick Send] [text "Send"]
  45. ]
  46. viewMessage : String -> Html msg
  47. viewMessage msg =
  48. div [] [ text msg ]

The interesting parts are probably the uses of WebSocket.send and WebSocket.listen.

For simplicity we will target a simple server that just echos back whatever you type. So you will not be able to have the most exciting conversations in the basic version, but that is why we have exercises on these examples!