Current section

Files

Jump to
gluon src tcp_client.erl
Raw

src/tcp_client.erl

-module(tcp_client).
-compile([no_auto_import, nowarn_unused_vars]).
-export([init/2]).
-export_type([client_message/0]).
-type client_message() :: {receive_message, bitstring()} |
{send_message, gleam@bit_builder:bit_builder()} |
close.
-spec connect(binary(), integer()) -> glisten@socket:socket().
connect(Host, Port) ->
_assert_subject = gen_tcp:connect(
unicode:characters_to_list(Host),
Port,
[gleam@dynamic:from(erlang:binary_to_atom(<<"binary"/utf8>>))]
),
{ok, Client} = case _assert_subject of
{ok, _} -> _assert_subject;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"tcp_client"/utf8>>,
function => <<"connect"/utf8>>,
line => 22})
end,
Client.
-spec init(binary(), integer()) -> {gleam@erlang@process:subject(client_message()),
gleam@erlang@process:subject(client_message())}.
init(Host, Port) ->
Receiver = gleam@erlang@process:new_subject(),
_assert_subject@2 = gleam@otp@actor:start_spec(
{spec,
fun() ->
Client = connect(Host, Port),
Subj = gleam@erlang@process:new_subject(),
Client_selector = begin
_pipe = gleam_erlang_ffi:new_selector(),
_pipe@4 = gleam@erlang@process:selecting_record3(
_pipe,
erlang:binary_to_atom(<<"tcp"/utf8>>),
fun(_, Msg) -> _pipe@1 = Msg,
_pipe@2 = gleam@dynamic:bit_string(_pipe@1),
_pipe@3 = gleam@result:unwrap(_pipe@2, <<>>),
{receive_message, _pipe@3} end
),
_pipe@5 = gleam@erlang@process:selecting_record2(
_pipe@4,
erlang:binary_to_atom(<<"tcp_closed"/utf8>>),
gleam@function:constant(close)
),
gleam@erlang@process:selecting(
_pipe@5,
Subj,
fun gleam@function:identity/1
)
end,
{ready, Client, Client_selector}
end,
2000,
fun(Msg@1, Client@1) -> case Msg@1 of
{receive_message, Msg@2} ->
gleam@erlang@process:send(
Receiver,
{receive_message, Msg@2}
),
{continue, Client@1};
{send_message, Msg@3} ->
_assert_subject = tcp_ffi:send(Client@1, Msg@3),
{ok, _} = case _assert_subject of
{ok, _} -> _assert_subject;
_assert_fail ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail,
module => <<"tcp_client"/utf8>>,
function => <<"init"/utf8>>,
line => 71})
end,
{continue, Client@1};
close ->
_assert_subject@1 = tcp_ffi:close(Client@1),
{ok, _} = case _assert_subject@1 of
{ok, _} -> _assert_subject@1;
_assert_fail@1 ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail@1,
module => <<"tcp_client"/utf8>>,
function => <<"init"/utf8>>,
line => 75})
end,
{stop, normal}
end end}
),
{ok, Sender} = case _assert_subject@2 of
{ok, _} -> _assert_subject@2;
_assert_fail@2 ->
erlang:error(#{gleam_error => let_assert,
message => <<"Assertion pattern match failed"/utf8>>,
value => _assert_fail@2,
module => <<"tcp_client"/utf8>>,
function => <<"init"/utf8>>,
line => 39})
end,
{Sender, Receiver}.