Stopping Accept()

A

ales

Hi !

I have a thread waiting for incoming connections which then processes
data in its own way.
I want to stop and start thread manually using start() and close()
methods. The problem is, I don't know how to stop it in the middle of
accept() call.
The only way I can get out from accept is to connect localy to the same
port.
Any better idea ? Can I simulate IOException inside accept() ?

import java.net.* ;
import java.io.*;

public class MyServer extends Thread
{
private ServerSocket server = null ;
private boolean done = false ;
private int port = 0 ;

public MyServer(int port) throws Exception
{
this.port = port ;
this.server = new ServerSocket(port) ; // Starts server
}

public void run()
{
this.done = false ;
while (!this.done) {
Socket socket = this.server.accept(); // I want to kill this
if (!this.done) {
...processing socket
}
}
}

public void close()
{
this.done = true ;
try {
// This works but is lawzy
Socket s = new Socket("localhost", port) ;
} catch (Exception e) {}
}
}
 
G

Gordon Beaton

I have a thread waiting for incoming connections which then
processes data in its own way. I want to stop and start thread
manually using start() and close() methods. The problem is, I don't
know how to stop it in the middle of accept() call. The only way I
can get out from accept is to connect localy to the same port. Any
better idea ? Can I simulate IOException inside accept() ?

Instead of waiting in accept() all the time, create a non-blocking
ServerSocketChannel and use a Selector to determine when it is "safe"
to call accept(). Block in Selector.select() (with or without a
timeout) instead. Closing the ServerSocket should cause select() to
return (although I have not actually tested that behaviour).

Otherwise, connecting to the port locally is harmless and seems to
solve the problem...

/gordon
 
T

Thomas Schodt

ales said:
Any better idea ? Can I simulate IOException inside accept() ?

If you want to kill the listener socket anyway
you can use Socket.close().
 
S

Stefan Schulz

to call accept(). Block in Selector.select() (with or without a
timeout) instead. Closing the ServerSocket should cause select() to
return (although I have not actually tested that behaviour).

Why not use Selector.wakeup, if you need to "break out" of the select?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top