Simple example of socket programming for Erlang

Source: Internet
Author: User

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

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.