Erlang的socket 编程简例

Erlang 中gen_tcp 用于编写TCP程序,gen_udp用于编写UDP程序。1个简单的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是不可靠的,1定要设1个超时时间,而且Reqeust最好小于500字节。

WebSocket, JS 和Erlang相结合,能够实现Web的绝大多数功能。

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » Erlang的socket 编程简例

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡