简单TCP服务器代码:
-module(my_socket_server).
-export([start/0,loop/1]).
start() ->
{ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4},%自定义打包规则,生成一个监听2345端口的socket
{reuseaddr, true},
{active, true}]),
{ok, Socket} = gen_tcp:accept(Listen),%生存一个新的Socket
gen_tcp:close(Listen),%把该监听关闭,不再生成新的socket
loop(Socket).
loop(Socket) ->
receive
{tcp, Socket, Bin} ->
io:format("Server received binary = ~p~n",[Bin]),
Str = binary_to_term(Bin),%解码
io:format("Server (unpacked) ~p~n",[Str]),
Reply = lib_misc:string2value(Str),
io:format('Server replying = ~p~n',[Reply]),
gen_tcp:send(Socket, term_to_binary(Reply)),%编码
loop(Socket);
{tcp_closed, Socket} ->
io:format("Server socket close~n")
end.
顺序服务器:
-module(my_socket_server2).
-compile(export_all).
start() ->
{ok, Liste