Search code examples
javaserversocket

How to get number of pending requests or accept requests without blocking in ServerSocket?


I created subclass of java.net.ServerSocket.

In run method I want to get all pending requests and send them error message.

How to do it with ServerSocket?

Here is my code:

public class SafeWalkServer extends ServerSocket implements Runnable {

    public SafeWalkServer(int port) throws IOException {
        super(port);

    }

    @Override
    public void run() {
        try {
            boolean isShutdown = false;
            while (!isShutdown) {
                Socket client = accept();
                BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                PrintWriter writer = new PrintWriter(client.getOutputStream());

                if (clientText.startsWith(":RESET"))
**//at this point I need to send error message to all pending requests.**
                        Socket sock = accept(); 
}
}
}
}

I need either number of pending requests or non-blocking variant of accept?


Solution

  • You can do non-blocking sockets with ServerSocketChannel. call configureBlocking(false) to do non-blocking. There are many good tutorials (with sample code) like The Rox Java NIO Tutorial.