简单web sever改进版:串行服务器,一次只接受一个连接
代码:tcp_sequence_server.erl
编译运行web服务器:
测试:TCP学习(二)中的client代码测试
[img]http://dl2.iteye.com/upload/attachment/0110/1556/0dd25774-4605-3dda-bc66-cfa9608bc5ec.png[/img]
[img]http://dl2.iteye.com/upload/attachment/0110/1554/3fed8b30-b969-3a77-ba85-677810ffa444.png[/img]
代码:tcp_sequence_server.erl
-module(tcp_sequence_server).
-compile(export_all).
-define(TCP_OPT, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]).
start_server() ->
{ok, ListenSocket} = gen_tcp:listen(8888, ?TCP_OPT),
seq_loop(ListenSocket).
seq_loop(ListenSocket) ->
case gen_tcp:accept(ListenSocket) of
{ok, Socket} ->
loop_receive(Socket),
seq_loop(ListenSocket);
{error, Reason} ->
io:format("server accept socket error:~p~n",[Reason])
end.
loop_receive(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("server receive bin data :~p~n",[Bin]),
UnpackData = binary_to_term(Bin),
io:format("server receive data: ~p~n", [UnpackData]),
Reply = {reply, UnpackData},
io:format("server reply data: ~p~n", [Reply]),
gen_tcp:send(Socket, term_to_binary(Reply)),
loop_receive(Socket);
{tcp_closed, Socket} ->
io:format("server socket close :~p~n",[Socket])
after 3000 ->
io:format("server time out, close socket~n"),
gen_tcp:close(Socket)
end.
编译运行web服务器:
erlc tcp_sequence_server.erl
erl
tcp_sequence_server:start_server().
测试:TCP学习(二)中的client代码测试
[img]http://dl2.iteye.com/upload/attachment/0110/1556/0dd25774-4605-3dda-bc66-cfa9608bc5ec.png[/img]
[img]http://dl2.iteye.com/upload/attachment/0110/1554/3fed8b30-b969-3a77-ba85-677810ffa444.png[/img]