Created
January 6, 2014 22:16
-
-
Save prio/8290780 to your computer and use it in GitHub Desktop.
Elixir gen_server example
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
defmodule Tcprpc.Server do | |
use GenServer.Behaviour | |
defrecord State, port: nil, lsock: nil, request_count: 0 | |
def start_link(port) do | |
:gen_server.start_link({ :local, :tcprcp }, __MODULE__, port, []) | |
end | |
def start_link() do | |
start_link 1055 | |
end | |
def get_count() do | |
:gen_server.call(:tcprcp, :get_count) | |
end | |
def stop() do | |
:gen_server.cast(:tcprcp, :stop) | |
end | |
def init (port) do | |
{ :ok, lsock } = :gen_tcp.listen(port, [{ :active, true }]) | |
{ :ok, State.new(lsock: lsock, port: port), 0 } | |
end | |
def handle_call(:get_count, _from, state) do | |
{ :reply, { :ok, state.request_count }, state } | |
end | |
def handle_cast(:stop , state) do | |
{ :noreply, state } | |
end | |
def handle_info({ :tcp, socket, raw_data}, state) do | |
do_rpc socket, raw_data | |
{ :noreply, state.update_request_count(fn(x) -> x + 1 end) } # inc? | |
end | |
def handle_info(:timeout, state = State[lsock: lsock]) do | |
{ :ok, _sock } = :gen_tcp.accept lsock | |
{ :noreply, state } | |
end | |
def do_rpc(socket, raw_data) do | |
try do | |
result = Code.eval_string(raw_data) | |
:gen_tcp.send(socket, :io_lib.fwrite("~p~n", [result])) | |
catch | |
error -> :gen_tcp.send(socket, :io_lib.fwrite("~p~n", [error])) | |
end | |
end | |
end |
This is by far the most explicit and valuable info on :gen_server
along with :gen_tcp
. The :gen_server
part could however strongly benefit on being rewritten using the Elixir's GenServer
wrapper.
👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code as presented didn't work for me. I needed to:
use GenServer.Behaviour
touse GenServer
defstruct
instead ofdefrecord
%State{lsock: lsock, port: port}
instead ofState.new(lsock: lsock, port: port)
%{ state | request_count: state.request_count + 1 }
instead ofstate.update_request_count(fn(x) -> x + 1 end)
Here is a version that appears to work: