-module(hello).
-export([main/0,
server/0,
client/0
]).
main()->
io:format("module ~p~n", [?MODULE]),
spawn(hello, server,[]),
spawn(hello, client,[]),
ok.
server() ->
{ok, LSock} = gen_tcp:listen(5678, [binary, {packet, 0},
{active, false}]),
{ok, Sock} = gen_tcp:accept(LSock),
io:format("before recv~n"),
{ok, Bin} = do_recv(Sock, []),
io:format("after recv~n"),
ok = gen_tcp:close(Sock),
io:format("data ~p~n" , [Bin]),
Bin.
do_recv(Sock, Bs) ->
case gen_tcp:recv(Sock, 0) of
{ok, B} ->
do_recv(Sock, [Bs, B]);
{error, closed} ->
{ok, list_to_binary(Bs)}
end.
client() ->
SomeHostInNet = "localhost", % to make it runnable on one machine
{ok, Sock} = gen_tcp:connect(SomeHostInNet, 5678,
[binary, {packet, 0}]),
ok = gen_tcp:send(Sock, "Some Data"),
ok = gen_tcp:close(Sock).
erl
Erlang R14B04 (erts-5.8.5) [source] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]
Eshell V5.8.5 (abort with ^G)
1> c(hello).
{ok,hello}
2> hello:main().
module hello
ok
before recv
after recv
data <<"Some Data">>
3>