Detect HTTP connection using inet

In my mochiweb application, I am using a long HTTP request. I wanted to detect when the user connection had died, and I figured out how to do it:

Socket = Req:get(socket), inet:setopts(Socket, [{active, once}]), receive {tcp_closed, Socket} -> % handle clean up Data -> % do something end. 

This works when: the user closes the tab / browser or refreshes the page. However, when the Internet connection suddenly dies (say the Wi-Fi signal is lost suddenly) or when the browser crashes, I cannot detect tcp closure.

Am I missing something, or is there any other way to achieve this?

+6
erlang mochiweb inet
source share
3 answers

There is a TCP keepalive protocol , and it can be enabled using inet:setopts/2 under the {keepalive, Boolean} option.

I would suggest that you do not use it. Keep-alive timeouts and max-retries tend to be systemic, and in any case, this is not necessary. Using timeouts at the protocol level is better.

HTTP has a status code timeout code that you can send to the client if it seems dead.

Pay attention to the after clause in the receive blocks, which you can use to wait for data to wait or use the timer module, or use erlang:start_timer/3 . All of them have different performance characteristics and resource costs.

+2
source

There is no default value "keep alive" (but can be enabled, if supported ) TCP protocol: if there is when data exchange does not occur, it means "silent failure". You will need to consider this type of failure yourself, for example. implement some form of connection.

How does this affect HTTP? HTTP is a stateless protocol - this means that every request is independent of each other. The functionality of the "keep alive" HTTP does not change, that is, a "silent failure" can still occur.

Only during data exchange can this condition be detected (or when TCP Keep Alive is supported).

+1
source

I would suggest sending the application layer, supporting live messages through HTTP encoding. Make sure your client / server is smart enough to understand how to save messages and ignore them if they arrive on time or close, and reconnect again.

0
source

All Articles