Erlangsocket programming example

Source: Internet
Author: User

Erlangsocket programming example

In Erlang, gen_tcp is used to write TCP programs, and gen_udp is used to write UDP programs. A simple TCP server echo example:

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 Tcp echo client:

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 example

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, you must set a timeout Time, And Reqeust should be less than 500 bytes.

WebSocket, JS, and Erlang can be combined to implement the vast majority of Web functions.

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.