Guest User

Untitled

a guest
Nov 17th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. -module(server).
  2. -export([start/1]).
  3.  
  4. start(ListenPort) ->
  5. case gen_tcp:listen(ListenPort, [binary, {active, false}, {reuseaddr, true}]) of
  6. {ok, ListenSocket} ->
  7. accept(ListenSocket);
  8. {error, Reason} ->
  9. {error, Reason}
  10. end.
  11.  
  12. accept(ListenSocket) ->
  13. {ok,Socket} = gen_tcp:accept(ListenSocket),
  14. Pid = spawn(fun() ->
  15. error_logger:info_msg("connection accepted~n", []),
  16. loop(Socket) end),
  17. gen_tcp:controlling_process(Socket, Pid),
  18. inet:setopts(Socket, [{active, true}]),
  19. accept(ListenSocket).
  20.  
  21. loop(Socket) ->
  22. receive
  23. {msg, Nick, Channel, Msg} ->
  24. gen_tcp:send(Socket, ["/msg ", Nick, " ", Channel, " ", Msg]),
  25. loop(Socket);
  26. {tcp, Socket, Data} ->
  27. error_logger:info_msg("receive ~s~n", [Data]),
  28. case Data of
  29. <<"/nick ", Data2/binary>> ->
  30. Nick = trim(binary_to_list(Data2)),
  31. error_logger:info_msg("~w changes nick to ~s~n", [Socket, Nick]),
  32. gen_tcp:send(Socket, term_to_msg(core:nick(Nick))),
  33. loop(Socket);
  34. <<"/msg ", Data2/binary>> ->
  35. {Channel, Msg} = lists:splitwith(fun($ )->false;(_)->true end, binary_to_list(Data2)),
  36. error_logger:info_msg("~w msg ~s:~s~n", [Socket, Channel, Msg]),
  37. gen_tcp:send(Socket, term_to_msg(core:msg(Channel, if length(Msg) > 1 -> tl(Msg); true -> Msg end))),
  38. loop(Socket);
  39. <<"/join ", Data2/binary>> ->
  40. Channel = trim(binary_to_list(Data2)),
  41. error_logger:info_msg("~w joins ~s~n", [Socket, Channel]),
  42. gen_tcp:send(Socket, term_to_msg(core:join(Channel))),
  43. loop(Socket);
  44. <<"/part ", Data2/binary>> ->
  45. Channel = trim(binary_to_list(Data2)),
  46. error_logger:info_msg("~w leaves ~s~n", [Socket, Channel]),
  47. gen_tcp:send(Socket, term_to_msg(core:part(Channel))),
  48. loop(Socket);
  49. _ ->
  50. gen_tcp:send(Socket, core:error_msg()),
  51. loop(Socket)
  52. end;
  53. {tcp_closed, Socket} ->
  54. error_logger:info_msg("~w closes~n", [Socket])
  55. end.
  56.  
  57. term_to_msg(ok) ->
  58. "ok";
  59. term_to_msg({error, Msg}) ->
  60. "error: " ++ Msg.
  61.  
  62. trim(S) ->
  63. X = re:replace(S, "^[ \r\n]*", "", [{return,list}]),
  64. re:replace(X, "[ \r\n]*$", "", [{return,list}]).
Add Comment
Please, Sign In to add comment