In Erlang, gen_tcp is used to write TCP programs, and GEN_UDP is used to write UDP programs. A simple example of a TCP server echo:
Start_echo_server ()
{ok,listen}= Gen_tcp:listen (1234,[binary,{packet,4},{reuseaddr,true},{active,true}]),
{ok,socket}=get_tcp:accept (Listen),
Gen_tcp:close (Listen),
Loop (Socket).
Loop (Socket),
Receive
{Tcp,socket,bin}
Io:format ("serverreceived binary = ~p~n", [Bin])
Str= binary_to_term (Bin),
Io:format ("Server (unpacked) ~p~n", [Str]),
reply= Lib_misc:string2value (STR),
Io:format ("serverreplying = ~p~n", [Reply]),
Gen_tcp:send (Socket,term_to_binary (Reply)),
Loop (Socket);
{Tcp_closed,socket}
Io:format ("ServerSocket closed ~n")
End.
Example of the Echo Client for TCP:
Echo_client_eval (STR)
{Ok,socket} = gen_tcp:connect ("localhost", 2345,[binary,{packet,4}]),
ok= gen_tcp:send (Socket, Term_to_binary (STR)),
Receive
{tcp,socket,bin}->
Io:format ("clientreceived binary = ~p~n", [Bin]),
Val=binary_to_term (Bin),
Io:format ("Clientresult = ~p~n", [Val]),
Gen_tcp:close (Socket)
End.
UDP Server Sample
Udp_demo_server (Port),
{ok,socket}= Gen_udp:open (open,[binary]),
Loop (Socket).
Loop (Socket),
Receive
{udp,socket,host,port,bin}->
Binreply= ...,
Gen_udp:send (socket,host,port,binreply),
Loop (Socket)
End.
UDP Client Example:
Udp_demo_client (Request)
{ok,socket}= Gen_udp:open (0,[binary]),
ok= gen_udp:send (Socket, "localhost", 1234,request),
Value= Receive
{udp,socket,_,_,bin}-> {Ok,bin}
after2000-Error
End
Gen_udp:close (Socket),
Value
Note that because UDP is unreliable, be sure to set a time-out period, and reqeust preferably less than 500 bytes.
WebSocket, JS and Erlang combine to achieve most of the web's functionality.
Simple example of socket programming for Erlang