Article View: borland.public.jbuilder.java.api
Article #1292Dead Socket doesn't throw exception
From: Owen Green
Date: Mon, 01 Apr 2002 01:18
Date: Mon, 01 Apr 2002 01:18
67 lines
2633 bytes
2633 bytes
Hi,
I'm having a bit of trouble reliably detecting when a socket has been
disconnected from the other end. I've seen various opinions around the place
that a read or write should result in an exception when this has happened,
but the code below fails to produce one (at least on my system which is,
gack, w95).
I'm a bit stumped on what to do with this as there seems to be /no/ reliable
method for detecting this condition.
import java.net.*;
import java.io.IOException;
import java.util.Date;
public class SocketTest implements Runnable{
public void run(){
ServerSocket ss = null;
try {
ss = new ServerSocket(6666);
Socket s = ss.accept();
//disconnect immediately
s.shutdownInput();
s.shutdownOutput();
s.close();
s = null;
System.err.println(new Date().toString() + ": Shut Socket");
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
if(ss!=null){
try{
ss.close();
System.err.println(new Date().toString() + ": Shut Server");
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Thread(new SocketTest()).start();
try{
Socket s = new Socket("127.0.0.1",6666);
try{
Thread.sleep(5000);
}catch(InterruptedException ie){
ie.printStackTrace();
}
//will return -1 (indicating that there's nothing to read),
//BUT won't throw exception even though socket is defunct
System.err.println(s.getInputStream().read());
}catch(IOException ex){
ex.printStackTrace();
}
}
}
Technical Details
Message-ID:
<3ca7b409_1@dnews>Path:
arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-01!supernews.com!newsfeed.online.be!fu-berlin.de!news.boerde.de!nntp.cs.uni-magdeburg.de!PeerFeed.KWeb.on.ca!dnewsShow Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 1089d0,a31ecd0db1134a2e,start X-Google-Attributes: gid1089d0,public X-Google-ArrivalTime: 2002-03-31 17:15:56 PST From: "Owen Green" <owen@begonefoulmachine.kennulz.demon.co.uk> Newsgroups: borland.public.jbuilder.java.api Subject: Dead Socket doesn't throw exception Date: Mon, 1 Apr 2002 02:18:28 +0100 Lines: 69 Organization: Unique Interactive X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 5.00.2314.1300 X-MimeOLE: Produced By Microsoft MimeOLE V5.00.2314.1300 NNTP-Posting-Host: 217.134.230.106 Message-ID: <3ca7b409_1@dnews> X-Trace: dnews 1017623561 217.134.230.106 (31 Mar 2002 17:12:41 -0800) Path: arc1-ca.pugleaf.net!archiver1.google.com!news1.google.com!sn-xit-02!sn-xit-01!supernews.com!newsfeed.online.be!fu-berlin.de!news.boerde.de!nntp.cs.uni-magdeburg.de!PeerFeed.KWeb.on.ca!dnews