Server:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 |
- module(echo). - export([listen / 1 ]). - define(TCP_OPTIONS, [binary, {packet, 0 }, {active, false}, {reuseaddr,true}]). % Call echo:listen(Port) to start the service. listen(Port) - > {ok, LSocket} =
gen_tcp:listen(Port, ?TCP_OPTIONS), spawn(fun() - >accept1(LSocket) end), spawn(fun() - >accept2(LSocket) end). % Wait for
incoming connections and
spawn the echo loop when we get one. accept1(LSocket) - > {ok, Socket} =
gen_tcp:accept(LSocket), spawn(fun() - > loop(Socket) end), accept1(LSocket). accept2(LSocket) - > {ok, Socket} =
gen_tcp:accept(LSocket), spawn(fun() - > loop(Socket) end), accept2(LSocket). % Echo back whatever data we receive on Socket. loop(Socket) - > case gen_tcp:recv(Socket, 0 ) of {ok, Data} - > % % gen_tcp:send(Socket, Data), % io: format ( " ~p~n" , [Data]), loop(Socket); {error, closed} - > ok end. |
Client:
-module(stress_test). -export([start/0]). start() -> tests(7789). tests(Port) -> io:format("starting~n"), spawn(fun() -> test(Port) end), spawn(fun() -> test(Port) end), spawn(fun() -> test(Port) end), spawn(fun() -> test(Port) end). test(Port) -> case gen_tcp:connect("127.0.0.1", Port, [binary, {packet, 0}]) of {ok, _} -> test(Port); _ -> test(Port) end.
erlang--echo_server,布布扣,bubuko.com
原文:http://www.cnblogs.com/vinsonliudk/p/3629816.html