<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=us-ascii">
<META NAME="Generator" CONTENT="MS Exchange Server version 6.5.7638.1">
<TITLE>How to check if a TCP socket is closed</TITLE>
</HEAD>
<BODY>
<!-- Converted from text/rtf format -->
<P><FONT SIZE=2 FACE="Arial">Hi all,</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">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.</FONT></P>
<P><FONT SIZE=2 FACE="Arial">loop(Socket) -></FONT>
<BR><FONT SIZE=2 FACE="Arial"> receive</FONT>
<BR> <FONT SIZE=2 FACE="Arial">something -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> do_something()</FONT>
<BR><FONT SIZE=2 FACE="Arial"> after 2000 -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> %% read from the socket to see if we can, timeout=0</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> case catch gen_tcp:recv(Socket, 0, 0) of</FONT>
<BR> <FONT SIZE=2 FACE="Arial">{error, timeout} -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> %% this is normal: no data</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> loop(Socket);</FONT>
<BR> <FONT SIZE=2 FACE="Arial">{error, Reason} -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> %% something wrong with the socket, we're done</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> done;</FONT>
<BR> <FONT SIZE=2 FACE="Arial">{'EXIT', Reason} -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> %% something worse with the socket, report it </FONT>
<BR> <FONT SIZE=2 FACE="Arial"> {error, Reason};</FONT>
<BR> <FONT SIZE=2 FACE="Arial">{ok, Data} -></FONT>
<BR> <FONT SIZE=2 FACE="Arial"> %% got some data, store it for when we really need it (in some gen_tcp:recv/2)</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> catch gen_tcp:unrecv(Args#arg.clisock, Data),</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> loop(Socket)</FONT>
<BR> <FONT SIZE=2 FACE="Arial"> end</FONT>
<BR><FONT SIZE=2 FACE="Arial"> end.</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">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?</FONT></P>
<P><FONT SIZE=2 FACE="Arial">I actually want to do this in a page in Yaws, so I do not have much freedom to make the socket 'active'.</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">*Erik.</FONT>
</P>
</BODY>
</HTML>