Skip to content

Commit

Permalink
PING/PONG -- Take #2
Browse files Browse the repository at this point in the history
This is the second implementation handling PING/PONG.

It feels a little cleaner, and the code is a bit simpler.

EXCEPT:

The parser generates an "artificial" message containing empty `sid` and
`body` fields.  Probably not a big deal, but looks a little strange.

Resolves #12
  • Loading branch information
Steve Newell committed Mar 23, 2017
1 parent 5250430 commit 4ab08f5
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/gnat.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ defmodule Gnat do
def handle_info({:tcp, tcp, data}, %{tcp: tcp, parser: parser}=state) do
{new_parser, messages} = Parser.parse(parser, data)
Enum.each(messages, fn({:msg, topic, sid, body}) ->
send state.receivers[sid], {:msg, topic, body}
case topic do
"PING" ->
Logger.debug "#{__MODULE__} Received PING, sending PONG"
:gen_tcp.send(state.tcp, "PONG\r\n")
_ ->
send state.receivers[sid], {:msg, topic, body}
end
end)
{:noreply, %{state | parser: new_parser}}
end
Expand Down
1 change: 1 addition & 0 deletions lib/gnat/parser.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ defmodule Gnat.Parser do
end

def parse(parser, "", parsed), do: {parser, Enum.reverse(parsed)}
def parse(parser, "PING\r\n", _), do: {parser, [{:msg, "PING", "", ""}]}
def parse(parser, bytes, parsed) do
{index, 2} = :binary.match(bytes, "\r\n")
{command, "\r\n"<>rest} = String.split_at(bytes, index)
Expand Down
6 changes: 6 additions & 0 deletions test/gnat/parser_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,10 @@ defmodule Gnat.ParserTest do
assert msg1 == {:msg, "t1", 1, "wat"}
assert msg2 == {:msg, "t2", 2, "dawg"}
end

test "parsing PING message" do
{parser_state, [parsed_message]} = Parser.new |> Parser.parse("PING\r\n")
assert parser_state.partial == ""
assert parsed_message == {:msg, "PING", "", ""}
end
end

0 comments on commit 4ab08f5

Please sign in to comment.