[Erlang 學習筆記] erlang socket 小小 demo

來源:互聯網
上載者:User

server端代碼:

-module(server).-export([start/0]).-export([stop/1]).start()->{ok,Listen}=gen_tcp:listen(8888, %%socket監聽的連接埠[binary, %%socket傳輸格式 binary:二進位 list:字元列表{packet,4}, %%有關對二進位包的解包{reuseaddr,true}, %%reuse address 複用串連過的ip地址??{active,true}]), %%{active ,true|false|once}被動或主動或一次接收資訊{ok,Socket}=gen_tcp:accept(Listen), %%接收發送至已監聽連接埠的資訊do(Socket,Listen). %%自訂處理do(Socket,Listen)->receive{tcp,Socket,Message}-> %%匹配時注意關鍵atom:tcp和tcp_close(建立的是基於tcp的socket)A=binary_to_term(Message), %%格式的轉換gen_tcp:send(Socket,term_to_binary(A));{tcp_closed,Socket}->stop(Listen),io:format("close ~n",[])end.stop(Listen)->gen_tcp:close(Listen),io:format("server close listen ~n",[]).

        在建立socket監聽的時候,有這麼個配置 {active,true},這參數的意思是自動接收資訊,配合gen_tcp:accept使用。但這種非阻塞接收方式會出現一種現象:資訊如洪水湧來,給server造成一定壓力,處理不及還會丟包。所以還有另一種接收方式,主動請求接收資訊(阻塞):配置{active,false|once},配合gen_tcp:accept和gen_tcp:recv還有setopt({active,once})使用,由server去控制接收資訊.



client端:

-module(client).-export([sendMessage/1,sendClose/0,waitAply/1]).sendMessage(Message)->{ok,Socket}= gen_tcp:connect("localhost",8888,[binary,{packet,4}]),%%串連gen_tcp:send(Socket,term_to_binary(Message)),%%發送B=term_to_binary(Message),io:format("client send ~w to server~n",[B]),sendClose()->{ok,Socket}= gen_tcp:connect("localhost",8888,[list,{packet,4}]),gen_tcp:close(Socket),%%關閉socket的時候會向串連的連接埠發送close資訊,server捕獲處理。io:format("client send close to server ~n",[]).

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.