Skip to content

Instantly share code, notes, and snippets.

@dcy
Created August 23, 2013 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcy/6317572 to your computer and use it in GitHub Desktop.
Save dcy/6317572 to your computer and use it in GitHub Desktop.
-module(robot).
-behaviour(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start/2]).
-define(IP, '127.0.0.1').
-define(PORT, 6666).
start(ClientNum, SendCount) ->
Fun = fun() ->
start_link(SendCount)
end,
for(0, ClientNum, Fun),
ok.
start_link(SendCount)->
case gen_server:start(?MODULE, [SendCount], []) of
{ok, _Pid}->
io:format("--robot start finish!-~n");
_->
io:format("--robot start fail!-~n"),
fail
end.
init([SendCount]) ->
process_flag(trap_exit,true),
case gen_tcp:connect(?IP, ?PORT, [binary, {packet,line}, {active, true}]) of
{ok, Socket} ->
spawn(fun() -> send_something(Socket, <<"PING\r\n">>, SendCount) end),
{ok, {}};
Reason ->
io:format("Connect to server failed: ~p~n", [Reason]),
{stop, normal, {}}
end.
send_something(Socket, Something, SendCount) ->
Fun = fun() ->
gen_tcp:send(Socket, Something)
end,
for(0, SendCount, Fun).
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({stop, Reason},State)->
{stop, normal, State};
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info(Info, State) ->
io:format("*****~p~n", [Info]),
{noreply, State}.
terminate(Reason, State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
for(Max, Max, _F) ->
[];
for(Min, Max, F) ->
[F() | for(Min+1, Max, F)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment