erlang
socket
-module (server).
-export ([start/0]).
-define (tcp_opts, [binary, {active,true}, {packet, 0},{reuseaddr, true}]).
%% 宏定义,当代码读到?errorlog,会用io:format("errorlog point")代替
-define (errorlog, io:format("errorlog point~n")).
start() ->
start(8888).
start(Port) ->
{ok, ListenSocket} = gen_tcp:listen(Port, ?tcp_opts),
register(server, spawn(fun() -> server_conn(ListenSocket) end)),
server_conn(ListenSocket).
server_conn(ListenSocket) ->
case gen_tcp:accept(ListenSocket) of
{ok, Socket} ->
io:format("connect succeed:~p~n",[Socket]),
server_route();
{error, Reason} ->
io:format("Socket closed : ~p~n",[Reason])
end.
server_route() ->
receive
{tcp, Socket, Data} ->
?errorlog,
gen_tcp:send(Socket, Data);
{tcp_closed, Socket} ->
gen_tcp:close(Socket)
end.
-module (client).
-export ([start/0]).
-define (tcp_opts, [binary, {packet, 0},{active, true}]).
start() ->
start("localhost",8888).
start(IP,Port) ->
register(client, spawn(fun() -> conn_client(IP,Port) end)).
conn_client(IP,Port) ->
case gen_tcp:connect(IP, Port, ?tcp_opts) of
{ok, Socket} ->
send_msg(Socket),
do_handle_client(Socket),
io:format("connection successed! ~w~n",[Socket]),
conn_client(IP,Port);
{error, Reason} ->
io:format("connect failed! ~n"),
exit(Reason)
end.
do_handle_client(Socket) ->
receive
{tcp, Socket, Packet} ->
recv_msg(Packet),
do_handle_client(Socket);
{tcp_closed, Socket} ->
gen_tcp:close(Socket)
end.
recv_msg(Packet) ->
Msg= binary_to_term(Packet),
io:format("Received Msg: ~p~n", [Msg]).
send_msg(Socket) ->
Msg = io:get_line('Input Your Msg:'),
Pack = term_to_binary(Msg),
io:format("Your msg: ~p~n", [Msg]),
gen_tcp:send(Socket, Pack),
send_msg(Socket).
在服务端中定义了start函数并把端口Port绑定为8888(和客户端对应端口),在第三步用gen_tcp模块的accept函数返回一个Socket进程(Java是说实例化了一个socket),接着在请求连接的下一个函数定义了接收进程(注意:register中启动了一个进程,这个就是接收进程),然后按照这些步骤定义之后,在Erlang shell打印输出:
1>server:start().
1>client:start().