I have some problem.
I want to associate process with one user (all requests from user receive one process, in HTTP 1.1 default keep-alive is on, and all requests send through one socket.)
I have following code:
loop(Sock, Reg_pid) ->
{ok, Conn} = gen_tcp:accept(Sock),
Pid = spawn(fun () -> client_socket(Conn,Reg_pid) end),
gen_tcp:controlling_process(Conn, Pid),
Pid ! {take, Conn}, %% race condition
loop(Sock, Reg_pid).
client_socket(S,Reg_pid) ->
io:format("in~n"),
receive
{take, So} ->
inet:setopts(So, [{active, once}]),
client_socket(So, Reg_pid);
{http, Socket, {http_request, _Method, {abs_path, _Path}, _Vers}} ->
case http_uri2:parse_path_query(_Path) of
{"/",[]} ->
io:format("Main pid - ~p ~n", [self()]),
gen_tcp:send(Socket, response("<a href='http://127.0.0.1:8080/register?name=Max'>Click</a>"));
{"/register",[{"name", Player_name}]} ->
io:format("Register pid - ~p ~n", [self()]);
_-> ok
end,
inet:setopts(Socket, [{active, once}]),
client_socket(Socket, Reg_pid);
{tcp_closed, Socket} ->
io:format("Socket ~w closed [~w]~n",[Socket,self()]);
% gen_tcp:close(Socket);
{tcp_error, Socket, Reason} ->
io:format("Error ~w closed [~w]~n",[Socket,self()]);
_-> ok
end.
When i connect through browser to server(index page) and then click link that return server, i have next result:
3> server:start(8080).
<0.43.0>
in
Main pid - <0.45.0>
in
in
Register pid - <0.46.0>
in
I can’t understand why my next request(click to link) receive other process(Register pid – <0.46.0>) ?
In this way, All requests from one user spawn new process, i want that all requsts from one users handle one process, how i can implament this ?
Thank you!
The browser may choose to not adhere to the Keep-Alive and instead create a new socket. Instead of trusting the Keep-Alive, you may consider sending a session cookie to the browser, associating the current session with a certain process. The session cookie will be sent by the browser for each request. Before you create a new process for new requests, check for the session cookie and see if there is a process associated with that session already.