LFE gen server Example
From Erlang Community
Contents |
Lisp Flavored Erlang: gen_server Example
This is a very simple gen_server example. It implements a locally registered server which keeps an integer as state and can return the current integer or the next one (in which case the state will increment).
Usage
- Save the code to count_server.lfe
- Compile it from the Erlang shell with lfe_comp:file(count_server).
Using From the Erlang Shell
Since LFE modules are just like normal modules, you use them the same way:
- Load the new module with l(count_server)
- Start up the server with count_server:start_link().
- Send it commands like count_server:current(). or count_server:next().
Using From the LFE Shell
TODO
Code
;; count_server.lfe ;; Simple gen_server example. (defmodule count_server (behavior 'gen_server) ;; gen_server exports (export (init 1) (handle_call 3) (handle_cast 2) (handle_info 2) (terminate 2) (code_change 3)) ;; public functions (export (start_link 0) (current 0) (next 0))) ;; gen_server implementation (defun init (args) #(ok 0))
(defun handle_call
(('next _ n)
(let ((new (+ n 1)))
(tuple 'reply (tuple 'ok new) new)))
(('current _ n)
(tuple 'reply (tuple 'ok n) n)))
(defun handle_cast (req state)
(tuple 'stop #(error not_implemented) state))
(defun handle_info (info state)
(tuple 'stop #(error not_implemented) state))
(defun terminate (reason state)
'ok)
(defun code_change (oldvsn state extra)
(tuple 'ok state))
;; public functions
(defun start_link ()
(: gen_server start_link #(local count_server) 'count_server () ()))
(defun current ()
(: gen_server call 'count_server 'current))
(defun next ()
(: gen_server call 'count_server 'next))

Digg It
Del.icio.us
Reddit
Facebook
Stumble Upon
Technorati

