I’m a erlang newbie.
When I read the Socket chapter from “Programming Erlang” and doing some examples according to the tutorial, there is a problem.
In the chapter “The Hybrid Approach (Partial Blocking)”, I do the following:
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 = lib_misc:string2value(Str),
io:format("Server replying = ~p~n",[Reply]),
gen_tcp:send(Socket, term_to_binary(Reply)),
inet:setopts(Socket,[binary,{active, once}]), %Configure socket as active
loop(Socket);
{tcp_closed, Socket} ->
io:format("Server socket closed~n")
end.
start()->
{ok,Listen} = gen_tcp:listen(2345,[binary,{packet,4},
{reuseaddr, true},
{active, once}]),
{ok, Socket} = gen_tcp:accept(Listen),
loop(Socket).
sendData(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.
Then I open one terminal like this:
$erl
server:start().
and open another terminal like this:
$erl
client:sendData(“1233”).
At server, it will output:
Server received binary = <<131,107,0,3,49,50,51>>
Server (unpacked) “123”
Server replying = 123
At client, it will output:
Client received binary = <<131,97,123>>
Client result=123
But when the client sendData second time, there is not any response at server.
Is there something wrong? Thank you.
You server listen only one connection. You start function should be in another loop too.