我是二郎新手。
当我从“Programming Erlang”中阅读“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 = 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.
然后我像这样打开一个终端:
$ erl
server:start().
然后打开另一个终端,如下所示:
$ erl
client:sendData("1233").
在服务器上,它将输出:
服务器收到二进制= << 131,107,0,3,49,50,51 >>
服务器(未包装)“123”
服务器回复= 123
在客户端,它将输出:
客户收到的二进制文件= << 131,97,123 >>
客户结果= 123
但是当客户端第二次发送sendData时,服务器上没有任何响应。
有什么不对?谢谢你。
最佳答案
您的服务器仅监听一个连接。您的启动功能也应该处于另一个循环中。
关于sockets - 设置事件模式 'once'后,套接字服务器无法接受数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9919223/