Re: Timeout question on a socket thread
My problem is more complicated than I thought. Again, my class is
annotated -- BUT, in run() I need to let it go for a maximim of
maxConnectedTime seconds. If that is exceeded, I need to clean up,
kill this thing. So I create a timer, and an ActionListener to go off
if maxConnectedTime seconds is exceeded. However, I am painted into a
corner and don;t know how to get out! I need to:
1. Be sure I can exit not only the ActionListener method inside the
Timer here, but the entire run() method, i.e. shut this thread down.
2. My cleanup really occurs in the finally block at the end of run().
I cannot simply put that into my ActionListener because of variable
restrictions (i.e. my variables are not final, and if I make surrogate
final variables per Eric's suggestion, I don't know what they are yet,
cannot even declare them.
If there was a way I could force an exception back out to run(), I
could get out of this nice and cleanly when the time was up. But it
seems that connot be done.
How do I get out of this corner?
public class SocketListener implements Runnable {
public void start() throws Exception {
try {
this.server = new ServerSocket(this.port, this.backlog,
this.bindAddress);
this.server.setSoTimeout(this.inactivityTimeOut * 1000);
listen();
}catch(Exception e){}
public void listen() {
this.threadPool.getInstance().run(this);
}
public void run() {
Timer timer1 = new Timer(this.maxConnectedTime * 1000,
new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e)
{
//we need to check on cleanup like in finally at end here
//additionally, we need to get out of here altogether
//not just return from this actionPerformed, but from the
//enclosing run()
}
});
timer1.start();
// Accept a connection
Socket socket = null;
try {
socket = this.server.accept();
}
catch (IOException e) {
}
// Create a new thread to accept the next connection
listen();
// CONSIDER: non-buffered readers/writers
BufferedInputStream inputBuffered = null;
OutputStream output = null;
StringBuilder request = null;
try {
inputBuffered = new BufferedInputStream(socket.getInputStream
());
output = socket.getOutputStream();
if (!socket.isClosed()) {
byte inputRead[] = new byte[4096];
int bytesRead;
while (0 <= (bytesRead = inputBuffered.read(inputRead, 0,
4096))) {
..............
} // END WHILE reading from client
}
}
catch (SocketException se) {
}
catch (Exception e) {
}
finally {
try {
if (timer1 != null) {
timer1.stop();
}
if (null != socket) {
log.info("Closing connection, cleaning up");
socket.close();
}
if (null != inputBuffered) {
inputBuffered.close();
}
if (null != output) {
output.close();
}
}
catch (Exception e) {
stackLog.error(e, e);
}
}
}
}