summaryrefslogtreecommitdiff
path: root/erlang/server.erl
blob: 2e4aec0ace57257c061eb0bfc6c2036fe20b969f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-module(server).
-behaviour(gen_server).

-export([main/0]).
-export([start_link/0, stop/0, message/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
		code_change/3]).

%%==============================================================================
%% Server API
%%==============================================================================

start_link() ->
	Result = gen_server:start_link({local, server}, server, [], []),
	io:fwrite("Server started.~n"),
	Result.

stop() ->
	gen_server:cast(server, shutdown).

message(Msg) ->
	gen_server:cast(server, Msg).


%%==============================================================================
%% gen_server callbacks
%%==============================================================================

init([]) ->
	file:open("server_log.txt", [write]).

handle_call(_Msg, _From, Fd) ->
	{reply, ok, Fd}.

handle_cast(shutdown, Fd) ->
	{stop, normal, Fd};

handle_cast(Msg, Fd) ->
	io:fwrite("Server writing into file: '~p'.~n", [Msg]),
	io:format(Fd, "~w~n", [Msg]),
	{noreply, Fd}.

code_change(_OldVsn, Fd, _Extra) ->
	{ok, Fd}.

terminate(_Reason, Fd) ->
	io:fwrite("Server is shutting down.~n"),
	file:close(Fd),
	ok.

handle_info(_Info, Fd) ->
	{noreply, Fd}.

main() ->
	start_link(),
	message(hoola),
	message(blrblrlb),
	message(wakawaka),
	stop().