最简单的Erlang Socket程序
server.erl:
1
-
module(server).
2 - export([start / 0 ]).
3
4 start() ->
5 {ok,Listen} = gen_tcp:listen( 2345 ,[binary,{packet, 4 },
6 {reuseaddr, true },
7 {active, true }]),
8 {ok,Socket} = gen_tcp:accept(Listen),
9 gen_tcp:close(Listen),
10 loop(Socket).
11
12 loop(Socket) ->
13 receive
14 {tcp,Socket,Bin} ->
15 io:format( " Server received binary = ~p~n " ,[Bin]),
16 Str = binary_to_term(Bin),
17 io:format( " Server (unpacked) ~p~n " ,[Str]),
18 Reply = Str ++ " ** MLGB! " ,
19 io:format( " Server replying = ~p~n " ,[Reply]),
20 gen_tcp:send(Socket,term_to_binary(Reply)),
21 loop(Socket);
22 {tcp_closed,Socket} ->
23 io:format( " Server socket closed~n " )
24 end.
client.erl:
2 - export([start / 0 ]).
3
4 start() ->
5 {ok,Listen} = gen_tcp:listen( 2345 ,[binary,{packet, 4 },
6 {reuseaddr, true },
7 {active, true }]),
8 {ok,Socket} = gen_tcp:accept(Listen),
9 gen_tcp:close(Listen),
10 loop(Socket).
11
12 loop(Socket) ->
13 receive
14 {tcp,Socket,Bin} ->
15 io:format( " Server received binary = ~p~n " ,[Bin]),
16 Str = binary_to_term(Bin),
17 io:format( " Server (unpacked) ~p~n " ,[Str]),
18 Reply = Str ++ " ** MLGB! " ,
19 io:format( " Server replying = ~p~n " ,[Reply]),
20 gen_tcp:send(Socket,term_to_binary(Reply)),
21 loop(Socket);
22 {tcp_closed,Socket} ->
23 io:format( " Server socket closed~n " )
24 end.
1
-
module(client).
2 - export([start / 1 ]).
3
4 start(Str) ->
5 {ok, Socket} =
6 gen_tcp:connect( " localhost " , 2345 , [binary, {packet, 4 }]),
7 ok = gen_tcp:send(Socket, term_to_binary(Str)),
8 receive
9 {tcp, Socket, Bin} ->
10 io:format( " Client received binary = ~p~n " , [Bin]),
11 Val = binary_to_term(Bin),
12 io:format( " Client result = ~p~n " , [Val]),
13 gen_tcp:close(Socket)
14 end.
编译:
2 - export([start / 1 ]).
3
4 start(Str) ->
5 {ok, Socket} =
6 gen_tcp:connect( " localhost " , 2345 , [binary, {packet, 4 }]),
7 ok = gen_tcp:send(Socket, term_to_binary(Str)),
8 receive
9 {tcp, Socket, Bin} ->
10 io:format( " Client received binary = ~p~n " , [Bin]),
11 Val = binary_to_term(Bin),
12 io:format( " Client result = ~p~n " , [Val]),
13 gen_tcp:close(Socket)
14 end.
1
Eshell
>
c(server).
2 Eshell > c(client).
启动server:
2 Eshell > c(client).
1
Eshell
>
server:start().
启动client:
1
Eshell
>
client:start("sb").
server端输出:
1
Server received binary = <<131,107,0,2,115,98>>
2 Server (unpacked) "sb"
3 Server replying = "sb** MLGB!"
4 Server socket closed
client端输出:
2 Server (unpacked) "sb"
3 Server replying = "sb** MLGB!"
4 Server socket closed
1
Client received binary = <<131,107,0,10,115,98,42,42,32,77,76,71,66,33>>
2 Client result = "sb** MLGB!"
2 Client result = "sb** MLGB!"