`

Erlang--TCP学习(三)串行web server篇

阅读更多
  简单web sever改进版:串行服务器,一次只接受一个连接

代码: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代码测试


  • 大小: 16.8 KB
  • 大小: 13.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics