server.erl:
-module(server).
-export([start/0]).
start() ->
{ok,Listen}=gen_tcp:listen(2345,[binary,{packet,4},
{reuseaddr,true},
{active,true}]),
{ok,Socket}=gen_tcp:accept(Listen),
gen_tcp:close(Listen),
loop(Socket).
loop(Socket) ->
receive
{tcp,Socket,Bin} ->
io:format("Server received binary = ~p~n",[Bin]),
Str=binary_to_term(Bin),
io:format("Server (unpacked) ~p~n",[Str]),
Reply= Str ++ "** MLGB!",
io:format("Server replying = ~p~n",[Reply]),
gen_tcp:send(Socket,term_to_binary(Reply)),
loop(Socket);
{tcp_closed,Socket} ->
io:format("Server socket closed~n")
end.
client.erl:
-module(client).
-export([start/1]).
start(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("Client received binary = ~p~n", [Bin]),
Val = binary_to_term(Bin),
io:format("Client result = ~p~n", [Val]),
gen_tcp:close(Socket)
end.
编译:
Eshell > c(server).
Eshell > c(client).
启动server:
Eshell > server:start().
启动client:
Eshell > client:start("sb").
server端输出:
Server received binary = <<131,107,0,2,115,98>>
Server (unpacked) "sb"
Server replying = "sb** MLGB!"
Server socket closed
client端输出:
Client received binary = <<131,107,0,10,115,98,42,42,32,77,76,71,66,33>>
Client result = "sb** MLGB!"