iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 18
0
Modern Web

學會Elm寫前端系列 第 18

18 elm 上使用websocket

websockets

如果你要架個聊天室的話,常用的通訊協定會是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


上一篇
17 使用webpack來打包elm
下一篇
19 讓elm看懂Markdown
系列文
學會Elm寫前端30

尚未有邦友留言

立即登入留言