diff options
author | Jasper Van der Jeugt | 2020-07-29 18:56:31 +0200 |
---|---|---|
committer | Jasper Van der Jeugt | 2020-07-29 18:56:31 +0200 |
commit | 057d954fe8d3265fc122f4a3066eab15eb7653d3 (patch) | |
tree | 0add61cd3113efd4d0def3dbdeb52c9fab6a8321 /client | |
parent | 0e2f396f26a490cfdd13b3fbda54a8ca53a28e26 (diff) |
Client talking to server
Diffstat (limited to '')
-rw-r--r-- | client/index.html | 11 | ||||
-rw-r--r-- | client/src/Client.elm | 26 |
2 files changed, 31 insertions, 6 deletions
diff --git a/client/index.html b/client/index.html index 3803738..75ee56d 100644 --- a/client/index.html +++ b/client/index.html @@ -9,6 +9,17 @@ <script type="text/JavaScript" src="/assets/client.js"></script> <script> var app = Elm.Client.init({node: document.querySelector("main")}); + + var roomId = document.location.pathname.split("/")[2]; + var url = "ws://" + document.location.host + + "/rooms/" + roomId + "/events"; + var socket = new WebSocket(url); + app.ports.webSocketOut.subscribe(function(message) { + socket.send(message); + }); + socket.addEventListener("message", function(event) { + app.ports.webSocketIn.send(event.data); + }); </script> </body> </html> diff --git a/client/src/Client.elm b/client/src/Client.elm index cc144e2..f4247f7 100644 --- a/client/src/Client.elm +++ b/client/src/Client.elm @@ -1,11 +1,16 @@ -module Client exposing (main) +port module Client exposing (main) import Browser import Html exposing (Html) import Url exposing (Url) -type Message +port webSocketIn : (String -> msg) -> Sub msg +port webSocketOut : String -> Cmd msg + +type Msg = Ignore + | Send + | WebSocketIn String type Model = Error String @@ -18,7 +23,7 @@ parseRoomId url = case String.split "/" url.path of _ :: "rooms" :: roomId :: _ -> Ok roomId _ -> Err <| "Invalid path: " ++ url.path -view : Model -> List (Html Message) +view : Model -> List (Html Msg) view model = case model of Error str -> [ Html.h1 [] [Html.text "Error"] @@ -28,13 +33,22 @@ view model = case model of [ Html.h1 [] [Html.text <| "Room " ++ room.id] ] -main : Program () Model Message +subscriptions : Model -> Sub Msg +subscriptions model = webSocketIn WebSocketIn + +update : Msg -> Model -> (Model, Cmd Msg) +update msg model = case msg of + Ignore -> (model, Cmd.none) + Send -> (model, webSocketOut "Hi") + WebSocketIn str -> Debug.log str (model, Cmd.none) + +main : Program () Model Msg main = Browser.application { init = \() url key -> case parseRoomId url of Err str -> (Error <| "Could not parse room ID: " ++ str, Cmd.none) Ok roomId -> (JoinRoom {id = roomId}, Cmd.none) - , update = \_ model -> (model, Cmd.none) - , subscriptions = \_ -> Sub.none + , update = update + , subscriptions = subscriptions , view = \model -> {title = "Client", body = view model} , onUrlChange = \url -> Ignore , onUrlRequest = \urlRequest -> Ignore |