Skip to content

Commit

Permalink
feat: send/3 to sends to a NNTP socket
Browse files Browse the repository at this point in the history
Similar to `gen_tcp:send/2`, but also wait for response from server.

Commands are sent with newline appended.
  • Loading branch information
sntran committed Mar 1, 2021
1 parent a5b850a commit 8ad00ec
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
5 changes: 5 additions & 0 deletions lib/gen_nntp.ex
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ defmodule GenNNTP do
"""
defdelegate connect(address \\ "localhost", port \\ 119, options \\ []), to: :gen_nntp

@doc """
Sends a command and receives server's response.
"""
defdelegate send(socket, command, args \\ []), to: :gen_nntp

@callback init(any()) ::
{:ok, state} | {:ok, state, timeout | :hibernate} |
:ignore | {:stop, reason :: term}
Expand Down
17 changes: 16 additions & 1 deletion src/gen_nntp.erl
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
connect/0,
connect/1,
connect/2,
connect/3
connect/3,
send/2,
send/3
]).

%% gen_server callbacks
Expand Down Expand Up @@ -128,6 +130,19 @@ connect(Address, Port, _Options) ->
{error, Reason}
end.

%%-------------------------------------------------------------------
%% @doc Sends a command to a NNTP socket
%%
%% The function will also wait for the response from server.
%% @end
%%-------------------------------------------------------------------
send(Socket, Commamd) ->
send(Socket, Commamd, []).

send(Socket, Command, _Args) when is_binary(Command) ->
ok = gen_tcp:send(Socket, <<Command/binary, "\r\n">>),
gen_tcp:recv(Socket, 0, 1000).

%% ==================================================================
%% ranch_protocol Callbacks
%% ==================================================================
Expand Down
21 changes: 21 additions & 0 deletions test/gen_nntp_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,27 @@ defmodule GenNNTPTest do

end

describe "send/3" do

setup do
GenNNTP.start(TestNNTPServer, [], [])
{:ok, socket, _greeting} = GenNNTP.connect()

%{socket: socket}
end

test "sends QUIT command", %{socket: socket} do
assert {:ok, response} = GenNNTP.send(socket, "QUIT", [])
assert response =~ ~r/^205 /
end

test "send/2 default to empty arguments", %{socket: socket} do
assert {:ok, response} = GenNNTP.send(socket, "QUIT")
assert response =~ ~r/^205 /
end

end

describe "@callback init/1" do

test "is called when a client connects to it" do
Expand Down

0 comments on commit 8ad00ec

Please sign in to comment.