Erlang gen_tcp is used to write a TCP program, GEN_UDP to write a UDP program. A simple example of a TCP server echo :
Copy Code code as follows:
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.
The Echo client example for TCP:
Copy Code code as follows:
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
Copy Code code as follows:
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:
Copy Code code as follows:
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, it is important to set a time-out period, and reqeust is preferably less than 500 bytes.
WebSocket, JS and Erlang combine to achieve most of the web's functionality.