Erlang的socket 編程簡例,erlangsocket

來源:互聯網
上載者:User

Erlang的socket 編程簡例,erlangsocket

Erlang 中gen_tcp 用於編寫TCP程式,gen_udp用於編寫UDP程式。一個簡單的TCP伺服器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.

 

Tcp 的echo用戶端樣本:

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樣本

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 樣本:

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

注意,因為UDP是不可靠的,一定要設一個逾時時間,而且Reqeust最好小於500位元組。

WebSocket, JS 和Erlang相結合,能夠實現Web的絕大多數功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.