Skip to content

Commit

Permalink
Add support for emscripten websocket API
Browse files Browse the repository at this point in the history
Signed-off-by: Paul Guyot <[email protected]>
  • Loading branch information
pguyot committed Jan 28, 2025
1 parent f8f4753 commit 96793bf
Show file tree
Hide file tree
Showing 21 changed files with 1,402 additions and 65 deletions.
1 change: 1 addition & 0 deletions examples/emscripten/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ include(BuildErlang)
pack_runnable(run_script run_script estdlib eavmlib)
pack_runnable(call_cast call_cast eavmlib)
pack_runnable(html5_events html5_events estdlib eavmlib)
pack_runnable(echo_websocket echo_websocket estdlib eavmlib)
pack_runnable(wasm_webserver wasm_webserver estdlib eavmlib)
150 changes: 150 additions & 0 deletions examples/emscripten/echo_websocket.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
%
% This file is part of AtomVM.
%
% Copyright 2025 Paul Guyot <[email protected]>
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
% http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.
%
% SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
%

-module(echo_websocket).
-export([start/0]).

-define(ECHO_WEBSOCKET_URL, <<"wss://echo.websocket.org">>).

start() ->
register(main, self()),
Supported = websocket:is_supported(),
if
Supported ->
emscripten:run_script(
[
<<"window.document.getElementById('supported').innerHTML = 'yes';">>,
<<"window.document.getElementById('send-button').onclick = () => { Module.cast('main', window.document.getElementById('send-text').value); };">>
],
[main_thread, async]
),
websocket_loop();
true ->
emscripten:run_script(
[
<<"window.document.getElementById('supported').innerHTML = 'no';">>
],
[main_thread, async]
)
end.

websocket_loop() ->
Websocket = websocket:new(?ECHO_WEBSOCKET_URL),
websocket_loop(Websocket).

websocket_loop(Websocket) ->
ReadyState = websocket:ready_state(Websocket),
URL = websocket:url(Websocket),
Protocol = websocket:protocol(Websocket),
Extensions = websocket:extensions(Websocket),
emscripten:run_script(
[
<<"window.document.getElementById('ready-state').innerHTML = '">>, atom_to_list(ReadyState), <<"';">>,
<<"window.document.getElementById('url').innerHTML = '">>, URL, <<"';">>,
<<"window.document.getElementById('protocol').innerHTML = '">>, Protocol, <<"';">>,
<<"window.document.getElementById('extensions').innerHTML = '">>, Extensions, <<"';">>
],
[main_thread, async]
),
receive
{emscripten, {cast, Message}} ->
emscripten:run_script(
[
<<"const e = window.document.createElement('div');">>,
<<"e.classList.add('client-msg');">>,
<<"e.append(\"">>,
escape_js_str(binary_to_list(Message)),
<<"\");">>,
<<"window.document.getElementById('transcript').appendChild(e);">>
],
[main_thread, async]
),
ok = websocket:send(Websocket, Message),
websocket_loop(Websocket);
{websocket_open, Websocket} ->
emscripten:run_script(
[
<<"window.document.getElementById('send-text').disabled = false;">>,
<<"window.document.getElementById('send-button').disabled = false;">>
],
[main_thread, async]
),
websocket_loop(Websocket);
{websocket, Websocket, Data} ->
emscripten:run_script(
[
<<"const e = window.document.createElement('div');">>,
<<"e.classList.add('server-msg');">>,
<<"e.append(\"">>,
escape_js_str(binary_to_list(Data)),
<<"\");">>,
<<"window.document.getElementById('transcript').appendChild(e);">>
],
[main_thread, async]
),
websocket_loop(Websocket);
{websocket_error, Websocket} ->
emscripten:run_script(
[
<<"window.document.getElementById('send-text').disabled = false;">>,
<<"window.document.getElementById('send-button').disabled = false;">>,
<<"const e = window.document.createElement('div');">>,
<<"e.classList.add('error-msg');">>,
<<"e.append('Error');">>,
<<"window.document.getElementById('transcript').appendChild(e);">>
],
[main_thread, async]
);
{websocket_closed, Websocket, {WasClean, Code, Reason}} ->
emscripten:run_script(
[
<<"window.document.getElementById('send-text').disabled = true;">>,
<<"window.document.getElementById('send-button').disabled = true;">>,
<<"const e = window.document.createElement('div');">>,
<<"e.classList.add('close-msg');">>,
<<"const wasClean = window.document.createElement('p');">>,
<<"wasClean.append(\"">>, atom_to_list(WasClean), <<"\");">>,
<<"e.appendChild(wasClean);">>,
<<"const code = window.document.createElement('p');">>,
<<"code.append(\"">>, integer_to_list(Code), <<"\");">>,
<<"e.appendChild(code);">>,
<<"const reason = window.document.createElement('p');">>,
<<"reason.append(\"">>, escape_js_str(binary_to_list(Reason)), <<"\");">>,
<<"e.appendChild(reason);">>,
<<"window.document.getElementById('transcript').appendChild(e);">>
],
[main_thread, async]
);
Other ->
io:format("Unexpected message ~p\n", [Other]),
websocket_loop(Websocket)
end.

escape_js_str(Str) ->
escape_js_str(Str, []).

escape_js_str([$" | Tail], Acc) ->
escape_js_str(Tail, ["\\\"" | Acc]);
escape_js_str([$\n | Tail], Acc) ->
escape_js_str(Tail, ["<br />" | Acc]);
escape_js_str([C | Tail], Acc) ->
escape_js_str(Tail, [C | Acc]);
escape_js_str([], Acc) ->
lists:reverse(Acc).
88 changes: 88 additions & 0 deletions examples/emscripten/echo_websocket.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<!--
This file is part of AtomVM.
Copyright 2025 Paul Guyot <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later
-->
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>AtomVM echo websocket example</title>
<style type="text/css">
#transcript {
margin: 1ex 0;
padding: 1ex;
display: flex;
flex-direction: column;
width: 40em;
border: 1px dotted black;
}
#transcript div {
border-bottom-color: rgb(229, 231, 235);
border-radius: 8px;
border-radius: 8px;
border-style: solid;
border-width: 0px;
}
.client-msg {
margin: 1ex;
padding: 2ex;
background-color: rgb(22, 163, 74);
color: white;
align-self: flex-end;
}
.server-msg {
margin: 1ex;
padding: 2ex;
background-color: rgb(239, 239, 239);
color: black;
align-self: flex-start;
}
.error-msg {
margin: 2ex;
background-color: rgba(239, 68, 68);
color: white;
align-self: flex-start;
}
</style>
</head>
<body>
<h1>Echo websocket example</h1>
<p>
This example demonstrates use of websocket API by connecting to
demo API at echo.websocket.org.
</p>
<p>Websockets are supported by this browser: <span id="supported">N/A</span></p>
<p>Websocket ReadyState: <span id="ready-state">N/A</span></p>
<p>Websocket URL: <span id="url">N/A</span></p>
<p>Websocket Protocol: <span id="protocol">N/A</span></p>
<p>Websocket Extensions: <span id="extensions">N/A</span></p>

<div id="transcript"></div>
<input type="text" name="text" id="send-text" disabled></input>
<button id="send-button" disabled>Send</button>

<script>
// Arguments are loaded using fetch API.
// wasm_webserver serves under /build/ files in build subdirectory.
var Module = {
arguments: ["/build/examples/emscripten/echo_websocket.avm"],
};
</script>
<script async src="/AtomVM.js"></script>
</body>
</html>
1 change: 1 addition & 0 deletions examples/emscripten/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ <h1>AtomVM emscripten examples</h1>
<li><a href="run_script.html">Run script</a></li>
<li><a href="call_cast.html">Call &amp; cast</a></li>
<li><a href="html5_events.html">HTML5 Events</a></li>
<li><a href="echo_websocket.html">Echo websocket</a></li>
</ul>
</body>
</html>
1 change: 1 addition & 0 deletions libs/eavmlib/src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ set(ERLANG_MODULES
timer_manager
timestamp_util
uart
websocket
)

pack_archive(eavmlib ${ERLANG_MODULES})
Expand Down
Loading

0 comments on commit 96793bf

Please sign in to comment.