The moose likes Sockets and Internet Protocols and the fly likes Tough one: remote socket closed Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply Bookmark "Tough one: remote socket closed" Watch "Tough one: remote socket closed" New topic
Author

Tough one: remote socket closed

Ben Roy
Ranch Hand

Joined: Nov 01, 2000
Posts: 70
This server I'm working on spawns a new thread for each user that connects. It passes the socket, which the thread uses to make a new BufferedReader. Then it has a while loop:
while(keepGoing)
{
in.readLine();
doStuff();
Thread.sleep();
}
This is obviously an approximation. Anyway, it recognizes a disconnect command, in which case the thread cleans up and kills itself. But if someone just closes the telnet session they have open, the thread doesn't die (why should it?) and keep trying to read null, which also does all kinds of other nasty stuff. So how do I know if that particular connection was closed?
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

You can test the readLine() for a return of -1. Since nothing in the ASCII range is negative, getting this value back means sumpn ain't right with the connection. Then just close() on that case.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Ben Roy
Ranch Hand

Joined: Nov 01, 2000
Posts: 70
So readLine() returns -1 when it fails to read anything? Not null?
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Tough one: remote socket closed
 
Similar Threads
Java NIO socket communication: why can I still send data after the server closed the connection?
Socket open/close
SocketException
Client Server
Creating a Pipe that connects 2 sockets