websockets work

This commit is contained in:
2025-10-21 17:12:59 -07:00
parent 7ed8b12c4e
commit 079c47962a
5 changed files with 206 additions and 142 deletions
+59 -4
View File
@@ -222,11 +222,13 @@ handle_request(Sock, R = #request{method = M, path = P}) when M =/= undefined, P
route(Sock, M, P, R).
route(Sock, get, Route, _Request) ->
route(Sock, get, Route, Request) ->
case Route of
<<"/">> -> home(Sock);
<<"/default.css">> -> default_css(Sock);
_ -> http_err(Sock, 404)
<<"/">> -> home(Sock);
<<"/default.css">> -> default_css(Sock);
<<"/ws-test-echo.html">> -> ws_test_echo_html(Sock);
<<"/ws/echo">> -> ws_echo(Sock, Request);
_ -> http_err(Sock, 404)
end;
route(Sock, post, Route, Request) ->
case Route of
@@ -237,6 +239,46 @@ route(Sock, _, _, _) ->
http_err(Sock, 404).
ws_echo(Sock, Request) ->
try
ws_echo2(Sock, Request)
catch
X:Y:Z ->
tell(error, "CRASH ws_echo: ~tp:~tp:~tp", [X, Y, Z]),
http_err(Sock, 500)
end.
ws_echo2(Sock, Request) ->
tell("~p: ws_echo request: ~tp", [?LINE, Request]),
case fd_ws:handshake(Request) of
{ok, Response} ->
tell("~p: ws_echo response: ~tp", [?LINE, Response]),
respond(Sock, Response),
tell("~p: ws_echo: entering loop", [?LINE]),
ws_echo_loop(Sock);
Error ->
tell("ws_echo: error: ~tp", [Error]),
http_err(Sock, 400)
end.
ws_echo_loop(Sock) ->
ws_echo_loop(Sock, [], <<>>).
ws_echo_loop(Sock, Frames, Received) ->
tell("~p: ws_echo_loop: entering loop", [?LINE]),
case fd_ws:recv(Sock, Received, 5*fd_ws:min(), Frames) of
Result = {ok, Message, NewFrames, NewReceived} ->
tell("~p: ws_echo_loop ok: ~tp", [?LINE, Result]),
% send the same message back
ok = fd_ws:send(Sock, Message),
ws_echo_loop(Sock, NewFrames, NewReceived);
Error ->
tell("ws_echo_loop: error: ~tp", [Error]),
fd_ws:send(Sock, {close, <<>>}),
error(Error)
end.
home(Sock) ->
%% fixme: cache
Path_IH = filename:join([zx:get_home(), "priv", "index.html"]),
@@ -263,6 +305,19 @@ default_css(Sock) ->
http_err(Sock, 500)
end.
ws_test_echo_html(Sock) ->
%% fixme: cache
Path_IH = filename:join([zx:get_home(), "priv", "ws-test-echo.html"]),
case file:read_file(Path_IH) of
{ok, Body} ->
Resp = #response{headers = [{"content-type", "text/html"}],
body = Body},
respond(Sock, Resp);
Error ->
io:format("~p error: ~p~n", [self(), Error]),
http_err(Sock, 500)
end.
wfcin(Sock, #request{enctype = json,
cookies = Cookies,
body = #{"wfcin" := Input}}) ->