How to check if a TCP socket is closed

Erik Reitsma (RY/ETM) erik.reitsma@REDACTED
Mon Feb 27 13:54:27 CET 2006


Hi all,

I have a TCP socket that is opened with {active, false}. Then I enter a
receive clause (in a loop) in which I do not want to read from the
socket, but I want to be informed when the socket is closed by the peer.
I have not found a solution other than the following.

loop(Socket) ->
    receive
	something ->
	   do_something()
    after 2000 ->
	    %% read from the socket to see if we can, timeout=0
	    case catch gen_tcp:recv(Socket, 0, 0) of
		{error, timeout} ->
		    %% this is normal: no data
		    loop(Socket);
		{error, Reason} ->
		    %% something wrong with the socket, we're done
		    done;
		{'EXIT', Reason} ->
		    %% something worse with the socket, report it	
		    {error, Reason};
		{ok, Data} ->
		    %% got some data, store it for when we really need
it (in some gen_tcp:recv/2)
		    catch gen_tcp:unrecv(Args#arg.clisock, Data),
		    loop(Socket)
	    end
    end.

I was looking for a way to check if a socket is closed without reading
from it, and a way to make a socket 'active' only for non-data messages.
Any suggestions?
I actually want to do this in a page in Yaws, so I do not have much
freedom to make the socket 'active'.

*Erik.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20060227/7c82284e/attachment.htm>


More information about the erlang-questions mailing list