Skip to content

Instantly share code, notes, and snippets.

@sshine
Created October 31, 2013 08:46
Show Gist options
  • Save sshine/7246248 to your computer and use it in GitHub Desktop.
Save sshine/7246248 to your computer and use it in GitHub Desktop.
-module(simple_chatserver).
-export([start/0]).
-define(PORT, 33333).
% External API function for starting chat server
start() ->
% Start a process for coordinating communication between clients
CoordinatorPid = spawn(fun() -> coordinator(dict:new()) end),
% Listen to a TCP socket and start a process that accepts incoming
% connections. The Parameters should be explained at some point.
Parameters = [binary, {reuseaddr, true}, {active, false}, {buffer, 1024}],
case gen_tcp:listen(?PORT, Parameters) of
{ok, ListenSocket} ->
spawn(fun() -> acceptor(ListenSocket, CoordinatorPid) end),
ok;
Otherwise ->
io:format("Cannot listen to socket: ~p~n", [Otherwise]),
error
end.
acceptor(ListenSocket, CoordinatorPid) ->
case gen_tcp:accept(ListenSocket) of
{ok, Socket} ->
WorkerRef = make_ref(),
WorkerPid = spawn(fun() -> worker_init(Socket, CoordinatorPid, WorkerRef) end),
CoordinatorPid ! {worker, WorkerRef, WorkerPid},
acceptor(ListenSocket, CoordinatorPid)
end.
coordinator(WorkerDict) ->
receive
{worker, WorkerRef, WorkerPid} ->
coordinator(dict:store(WorkerRef, WorkerPid, WorkerDict))
end.
worker_init(Socket, CoordinatorPid, WorkerRef) ->
inet:setopts(Socket, [{active, once}, {packet, line}]),
worker(CoordinatorPid, WorkerRef).
worker(CoordinatorPid, WorkerRef) ->
receive
{tcp, _Socket, Data} ->
io:format("Got message: ~p~n", [Data]),
gen_tcp:send(_Socket, <<"Hello!\r\n">>),
worker(CoordinatorPid, WorkerRef)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment