Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(server).
- -export([start/1]).
- start(ListenPort) ->
- case gen_tcp:listen(ListenPort, [binary, {active, false}, {reuseaddr, true}]) of
- {ok, ListenSocket} ->
- accept(ListenSocket);
- {error, Reason} ->
- {error, Reason}
- end.
- accept(ListenSocket) ->
- {ok,Socket} = gen_tcp:accept(ListenSocket),
- Pid = spawn(fun() ->
- error_logger:info_msg("connection accepted~n", []),
- loop(Socket) end),
- gen_tcp:controlling_process(Socket, Pid),
- inet:setopts(Socket, [{active, true}]),
- accept(ListenSocket).
- loop(Socket) ->
- receive
- {msg, Nick, Channel, Msg} ->
- gen_tcp:send(Socket, ["/msg ", Nick, " ", Channel, " ", Msg]),
- loop(Socket);
- {tcp, Socket, Data} ->
- error_logger:info_msg("receive ~s~n", [Data]),
- case Data of
- <<"/nick ", Data2/binary>> ->
- Nick = trim(binary_to_list(Data2)),
- error_logger:info_msg("~w changes nick to ~s~n", [Socket, Nick]),
- gen_tcp:send(Socket, term_to_msg(core:nick(Nick))),
- loop(Socket);
- <<"/msg ", Data2/binary>> ->
- {Channel, Msg} = lists:splitwith(fun($ )->false;(_)->true end, binary_to_list(Data2)),
- error_logger:info_msg("~w msg ~s:~s~n", [Socket, Channel, Msg]),
- gen_tcp:send(Socket, term_to_msg(core:msg(Channel, if length(Msg) > 1 -> tl(Msg); true -> Msg end))),
- loop(Socket);
- <<"/join ", Data2/binary>> ->
- Channel = trim(binary_to_list(Data2)),
- error_logger:info_msg("~w joins ~s~n", [Socket, Channel]),
- gen_tcp:send(Socket, term_to_msg(core:join(Channel))),
- loop(Socket);
- <<"/part ", Data2/binary>> ->
- Channel = trim(binary_to_list(Data2)),
- error_logger:info_msg("~w leaves ~s~n", [Socket, Channel]),
- gen_tcp:send(Socket, term_to_msg(core:part(Channel))),
- loop(Socket);
- _ ->
- gen_tcp:send(Socket, core:error_msg()),
- loop(Socket)
- end;
- {tcp_closed, Socket} ->
- error_logger:info_msg("~w closes~n", [Socket])
- end.
- term_to_msg(ok) ->
- "ok";
- term_to_msg({error, Msg}) ->
- "error: " ++ Msg.
- trim(S) ->
- X = re:replace(S, "^[ \r\n]*", "", [{return,list}]),
- re:replace(X, "[ \r\n]*$", "", [{return,list}]).
Add Comment
Please, Sign In to add comment