Simple example of socket programming in Erlang _erlang

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.