功能简介:
实现简单的echo客户端和服务器,客户端发送消息给服务器,服务器将消息原样返回给客户端。比如,客户端发送“hello”给服务器,服务器返回“hello”给客户端。本博客客户端写了两个版本,初始版本发送的是一次性消息,消息发送完毕后关闭连接,改进版本接受键盘输入消息,按下回车键后将消息发送给服务器,客户端输入“close”为结束标志,关闭客户端连接。改进版本可连续发送多条消息,直至输入“close”结束连接。
服务器端文件:echo_server.erl
-module(echo_server).
-export([start/0]).
start() ->
{ok,Listen}=gen_tcp : Listen(5001,[binary,{packet,4},{reuseaddr,true},{active,true}]),
loop_listen(Listen).
%%注册新进程控制单次连接的Socket,负责处理Socket的连接;而原进程负责监听
loop_listen(Listen) ->
{ok,Socket}=gen_tcp:accept(Listen),
Pid = spawn(fun()-> loop(Socket)end),
ok = gen_tcp:controlling_process(Socket,Pid),
loop_listen(Listen).
loop(Socket) ->
receive
{ tcp , Socket , Bin} ->
Data = binary_to_term(Bin),
io:format("Server receive : ~p~n",[Data]),
gen_tcp: send(Socket,Bin),
loop(Socket);
{tcp_closed,Socket} ->
gen_tcp:close(Socket)
end.
客户端文件初始版本:echo_client.erl
-module(echo_client).
-export([start/1]).
start(Str) ->
{ok,Socket}->gen_tcp:connect("localhost",5001,[binary,{packet,4}]),
ok = gen_tcp:send(Socket,term_to_binary(Str)),
receive
{tcp,Socket,Data} ->
io:format("client receive ~p~n",[binary_to_term(Data)]),
gen_tcp:close(Socket)
end.
客户端文件改进版本:echo_client2.erl
-module(echo_client2).
-export([start/0]).
start() ->
{ok,Socket}->gen_tcp:connect("localhost",5001,[binary,{packet,4}]),
loop(Socket).
loop(Socket) ->
Orign_str = io: get_line([]),
Len = string : len(Orign_str),
Final_str = string : left(Orign_str,Len-1),
case string:equal(Final_str,"closed" ) of
true -> gen_tcp:close(Socket);
_ ->
gen_tcp:send(Socket,term_to_binary(Str)),
receive
{tcp,Socket,Data} ->
io:format("client receive ~p~n",[binary_to_term(Data)]),
loop(Socket)
end
end.