我决定通过将服务器更改为并行服务器(如书中所述)来修改此线程中的代码,但它无法正常工作。根据“Programming Erlang”一书,以下代码应该是 presto-chango,但我在第 17 行遇到错误。这是并行服务器代码(完成的并行服务器在底部,这只是对最后一个线程上的旧服务器代码),
startp() ->
{ok, Listen} = gen_tcp:listen(4042, [binary, {packet, 0},
{reuseaddr, true},
{active, true}]),
spawn(fun() -> par_connect(Listen) end).
par_connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> par_connect(Listen) end),
loop(Socket).
这就是错误,
=ERROR REPORT==== 12-Feb-2013::23:05:13 ===
Error in process <0.35.0> with exit value: {{badmatch,{error,einval}},[{ps1,loop,1,[{file,"ps1.erl"},{line,17}]}]}
以下是并行服务器代码,我认为调用循环(套接字)的第 14 行参数有问题。也许是别的东西,我不知道?
-module(ps1).
-compile(export_all).
-import(lists, [reverse/1]).
startp() ->
{ok, Listen} = gen_tcp:listen(4042, [binary, {packet, 0},
{reuseaddr, true},
{active, true}]),
spawn(fun() -> par_connect(Listen) end).
par_connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
spawn(fun() -> par_connect(Listen) end),
loop(Socket).
loop(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
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 = string:to_upper(Str),
io:format("Server replying = ~p~n",[Reply]),
gen_tcp:send(Socket, term_to_binary(Reply)),
loop(Listen);
{tcp_closed, Socket} ->
io:format("Server socket closed~n")
end.
接下来是客户端代码,它也最终死于等待回复
c1:nano("list_to_tuple([2+3*4,10+20])").
nano got not answer to "list_to_tuple([2+3*4,10+20])"
{error,timeout}
-module(c1).
-compile(export_all).
-import(lists, [reverse/1]).
%old port 2345
nano(Str) ->
{ok, Socket} =
gen_tcp:connect("localhost", 4042,
[binary, {packet, 0}]),
ok = gen_tcp:send(Socket, term_to_binary(Str)),
R = receive
{tcp,Socket,Bin} ->
io:format("Client received binary = ~p~n",[Bin]),
Val = binary_to_term(Bin),
io:format("Client result = ~p~n",[Val]),
{ok,Val}
after 5000 ->
io:format("nano got no answer to ~p~n",[Str]),
{error,timeout}
end,
% gen_tcp:close(Socket),
R.