Last active
August 29, 2015 13:58
-
-
Save fsword/10017210 to your computer and use it in GitHub Desktop.
simple telnet server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*.swp | |
*.beam |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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