Skip to content

Instantly share code, notes, and snippets.

@fsword
Last active August 29, 2015 13:58
Show Gist options
  • Save fsword/10017210 to your computer and use it in GitHub Desktop.
Save fsword/10017210 to your computer and use it in GitHub Desktop.
simple telnet server
*.swp
*.beam
-module(telnet).
-export([start/0,serve/1]).
-define(PORT, 8765).
start() ->
{ok, ListenSocket} = gen_tcp:listen(?PORT, [binary, {packet,0},{active,true}]),
start_servers(ListenSocket).
start_servers(ListenSocket) ->
spawn(?MODULE, serve, [ListenSocket]).
serve(ListenSocket) ->
msg("listen on ~p",[ListenSocket]),
case gen_tcp:accept(ListenSocket) of
{ok, Socket} ->
msg("accepted: ~p",[Socket]),
start_servers(ListenSocket),
inet:setopts(Socket,[{active,true}]),
wait(Socket);
{error, closed} ->
msg("error: closed")
end.
wait(Socket) ->
receive
{tcp, Socket, <<"stop\r\n">>} ->
msg("stopping."),
gen_tcp:close(Socket);
{tcp, Socket, Data} ->
msg("received: ~ts",[Data]),
gen_tcp:send(Socket, <<"got it\r\n",Data/binary>>),
wait(Socket);
{tcp_closed, Socket} ->
msg("tcp_closed");
Any ->
msg("unkown: ~p", [Any])
end.
msg(Msg) ->
io:format(pid_to_list(self()) ++ " " ++ Msg ++ "~n").
msg(Msg, Params) ->
io:format(pid_to_list(self()) ++ " " ++ Msg ++ "~n", Params).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment