Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Created January 25, 2016 01:46
Show Gist options
  • Save maxdeliso/532b36bccb5f2a7a1d78 to your computer and use it in GitHub Desktop.
Save maxdeliso/532b36bccb5f2a7a1d78 to your computer and use it in GitHub Desktop.
erlang udp server

running from a shell:

max [ ~/src/erlang/hello ]$ erl Erlang/OTP 18 [erts-7.2.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V7.2.1 (abort with ^G) 1> c(hello). {ok,hello} 2> hello:start(). test ok 3>

running compiled erlang code:

erlc hello.erl

(writes hello.beam)

erl -noshell -s hello start -s init stop

"-s hello start" causes hello:start(). to be called

"-s init stop" causes init:stop(). to be called after the previous finishes

(otherwise erl will hang)

-module(hello).
-export([start/0]).
% entry point
start() ->
{ok, Sock} = inet_udp:open(1337),
io:format("opened UDP socket:~p~n", [Sock]),
loop(Sock).
% loop which holds socket ref and writes OK back to clients
loop(Sock) ->
receive
{udp, Socket, Host, Port, Bin} ->
io:format("got message:~p~n", [Bin]),
ok = inet_udp:send(Socket, Host, Port, "OK\n"),
loop(Sock)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment