-
-
Save asonge/6ac8c237e44ea9271cb816d44264a395 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(chat_server). | |
-export([start/1]). | |
handle_socket(Router, Client) -> | |
case gen_tcp:recv(Client, 0) of | |
{ok, "quit!} -> | |
gen_tcp:close(Client); | |
{ok, Data} -> | |
Router ! {msg, Client, Data} | |
handle_socket(Router, Client); | |
{error, closed} -> | |
io:write("Client quit\r\n"), | |
Router ! {delete, Client} | |
end. | |
loop(Router, Server) -> | |
{ok, Client} = gen_tcp:accept(Server), | |
gen_tcp:send(Client, "You are now connected!\r\n"), | |
Router ! {add, Client}, | |
spawn(fun() -> loop(Router, Server) end), | |
handle_socket(Router, Client). | |
route_msg([], _Client, _Data) -> | |
ok; | |
route_msg([Client|T], Client, Data) -> | |
route_msg(T, Client, Data); | |
route_msg([H|T], Client, Data) -> | |
Message = io_lib:format("~p: ~s", [Client, Data]), | |
gen_tcp:send(H, Message), | |
route_msg(T, Client, Data). | |
router(Clients) -> | |
io:format("Clients:~n"), | |
io:format("~p~n", [Clients]), | |
receive | |
{add, Client} -> | |
io:format("Added client: ~p~n", [Client]), | |
router(lists:append(Clients, [Client])); | |
{delete, Client} -> | |
io:format("Deleted client: ~p~n", [Client]), | |
router(lists:delete(Client, Clients)); | |
{msg, Client, Data} -> | |
io:format("Incoming ~p: ~s", [Client, Data]), | |
route_msg(Clients, Client, Data), | |
router(Clients) | |
end. | |
start(Port) -> | |
{ok, Server} = gen_tcp:listen(Port, [ binary, | |
{packet, 0}, | |
{active, false}, | |
{reuseaddr, true} ]), | |
Router = spawn(fun() -> router([]) end), | |
loop(Router, Server). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment