Browse files

Changed the way the close command is implemented

* server.erl
  Now implements stop with a stop command being sent
  to the socket

* server_tests.erl
  Test that stop command works
  • Loading branch information...
1 parent 0020551 commit 0e843351b43a201dfdb806f8108e2a908993fdbf Gianfranco Alongi committed Mar 11, 2012
Showing with 18 additions and 19 deletions.
  1. +16 −16 Two/Solution/src/server.erl
  2. +2 −3 Two/Solution/test/server_tests.erl
View
32 Two/Solution/src/server.erl
@@ -1,6 +1,6 @@
-module(server).
-export([start/1,
- stop/0]).
+ stop/1]).
-spec(start([{atom(),string() | integer()}]) -> ok).
start(Options) ->
@@ -13,16 +13,12 @@ start(Options) ->
{started,Pid,Ref} -> ok
end.
--spec(stop() -> ok).
-stop() ->
- Pid = self(),
- Ref = make_ref(),
- server ! {stop,Pid,Ref},
- receive
- {stopped,Ref} ->
- ok
- end.
-
+-spec(stop(non_neg_integer()) -> ok).
+stop(CommandPort) ->
+ {ok,Sock} = gen_tcp:connect("localhost",CommandPort,[{active,false}]),
+ gen_tcp:send(Sock,"stop"),
+ {ok,"stopping"} = gen_tcp:recv(Sock,0),
+ ok.
start({To,Ref},FilesDir,CommandPort) ->
{ok,Sock} = gen_tcp:listen(CommandPort,[{active,false}]),
@@ -31,9 +27,13 @@ start({To,Ref},FilesDir,CommandPort) ->
loop(FilesDir,Sock).
loop(_FilesDir,Sock) ->
- receive
- {stop,From,Ref} ->
- gen_tcp:close(Sock),
- unregister(server),
- From ! {stopped,Ref}
+ {ok,Session} = gen_tcp:accept(Sock),
+ case gen_tcp:recv(Session,0) of
+ {ok,"stop"} ->
+ gen_tcp:send(Session,"stopping"),
+ gen_tcp:close(Session),
+ gen_tcp:close(Sock);
+ {error,closed} ->
+ gen_tcp:close(Session),
+ loop(_FilesDir,Sock)
end.
View
5 Two/Solution/test/server_tests.erl
@@ -8,14 +8,13 @@ server_start_test() ->
{command_port,CommandPort}],
?assertMatch(ok,server:start(Options)),
assert_port_open(CommandPort),
- ?assertEqual(ok,server:stop()),
+ ?assertEqual(ok,server:stop(CommandPort)),
assert_port_closed(CommandPort).
-
%% --------------------------------------------------
assert_port_open(Port) ->
{ok,Sock} = gen_tcp:connect("localhost",Port,[]),
gen_tcp:close(Sock).
assert_port_closed(Port) ->
- {error,econnrefused} = gen_tcp:connect("localhost",Port,[]).
+ {error,econnrefused} = gen_tcp:connect("localhost",Port,[]).

0 comments on commit 0e84335

Please sign in to comment.