如果你要架個聊天室的話,常用的通訊協定會是websocket,除了json之外,其實還有elm-lang也有這個的module。安裝也是很簡單
elm-package install websocket
至於怎麼使用呢?這個也和Json或是javascript interop類似,先來一段在elm-lang 上的 example
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/web_sockets.html
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import WebSocket
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
echoServer : String
echoServer =
"wss://echo.websocket.org"
-- MODEL
type alias Model =
{ input : String
, messages : List String
}
init : (Model, Cmd Msg)
init =
(Model "" [], Cmd.none)
-- UPDATE
type Msg
= Input String
| Send
| NewMessage String
update : Msg -> Model -> (Model, Cmd Msg)
update msg {input, messages} =
case msg of
Input newInput ->
(Model newInput messages, Cmd.none)
Send ->
(Model "" messages, WebSocket.send echoServer input)
NewMessage str ->
(Model input (str :: messages), Cmd.none)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
WebSocket.listen echoServer NewMessage
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [onInput Input, value model.input] []
, button [onClick Send] [text "Send"]
, div [] (List.map viewMessage (List.reverse model.messages))
]
viewMessage : String -> Html msg
viewMessage msg =
div [] [ text msg ]
當你 import WebSocket
後呢,如果你要send websocket的訊息,譬如像這個在按鈕裡,你按了之後會通知update
, 會有一個 Send
裡頭的cmd 就會去呼叫 Websocket.send
, 讓 elm
runtime去寄出這個訊息。而接收的話同樣是在 subscriptions裡, 放一個Websocket.listen
這樣就完成了! 如果想要更瞭解,這樣有官方的websocket doc