Created
March 31, 2018 14:37
-
-
Save kauffmanes/4e427d581789cecf68283f26b0011540 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
%% @author kauff | |
%% @doc @todo Add description to serv1. | |
-module(serv1). | |
%% ==================================================================== | |
%% API functions | |
%% ==================================================================== | |
-export([start/0, start/1, stop/1]). | |
-define(TCP_OPTIONS, [{packet, 0}, {active, false}, {reuseaddr, true}]). | |
start() -> start(8080). | |
start(Port) -> | |
io:format("TCP server starting on Port ~p~n", [Port]), | |
%start a tcp server listening on this port | |
case gen_tcp:listen(Port, ?TCP_OPTIONS) of | |
{ok, LSocket} -> | |
% creates process to handle incoming connections | |
spawn(fun() -> server(LSocket) end); | |
{error, Reason} -> | |
{error, Reason} | |
end. | |
% handles incoming connections | |
server(LSocket) -> | |
case gen_tcp:accept(LSocket) of | |
{ok, Socket} -> | |
io:format("Incoming connection (~p)~n", [Socket]), | |
spawn(fun() -> handle_client(Socket) end), | |
server(LSocket); | |
Other -> | |
io:format("Wut ~w~n", [Other]), | |
ok | |
end. | |
% handle_clients | |
handle_client(Socket) -> | |
io:format("test~n"), | |
receive | |
{Socket, Bin} -> | |
io:format("Server received binary = ~p~n", [Bin]), | |
Str = binary_to_term(Bin), | |
Reply = string:to_upper(Str), | |
gen_tcp:send(Socket, term_to_binary(Reply)), | |
handle_client(Socket); | |
{tcp_closed, Socket} -> | |
io:format("Socket ~w closed [~w]~n",[Socket, self()]), | |
ok | |
end. | |
stop(Socket) -> | |
gen_tcp:close(Socket). | |
% listen (connection handler) | |
%% ==================================================================== | |
%% Internal functions | |
%% ==================================================================== | |
% FLOWS: | |
% [x] chat server starts and makes a new server process on the provided port | |
% [x] that process opens up for connections | |
% [] someone tries to join the chat, sending their username | |
% [] the chat server accepts their connection and adds them to the list of connections | |
% [] the chat server broadcasts to everyone that the new user has joined | |
% [] the user sends a message to the chat server | |
% [] the chat server sends this message to everyone connected | |
% [] another user joins and steps 3-6 repeat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment