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",[]).
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",[]).