Ashley
Ashley

Reputation: 2318

Handle exceptions without crashing socket server?

I am attempting to run a threaded socket server that handles multiple clients simultaneously. However after I telnet into the server and then exit in a non-graceful way, say by closing the window.

The server crashes and returns System.out.println("Runnable terminating with exception: " + e ); with e being java.Lang.NullPointerException.

My question is how can I simply close the socket and keep the server running even if something goes wrong in handleSession(), so that others can connect?

I am new to exceptions so my understand is still elementary.

publc class ThreadedHandler implements Runnable {
    Socket incoming;
    BufferedReader in;
    PrintWriter out;
    SortedTopicList topics;

    ThreadedHandler(Socket s) {
        incoming = s;
    }
    public void run() {
        try {
            handleSession(incoming);
        }catch (Exception e) {
            System.out.println("Runnable terminating with exception: " + e );
        }
        }

    public void handleSession(Socket client) {
        try {
            //Code goes here
        } catch (IOException e) {
            System.err.println(e.getMessage());
        } finally {
            shutdown();
        }
    }

    public void shutdown() {
        try {
            in.close();
            out.close();
            incoming.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}

My main method is as follows:

public class MessageBoardServer {

    public static void main(String[] args) {
        Thread t;
        try {
            ServerSocket ss = new ServerSocket(118118);
            while(true) {
                Socket session = ss.accept();
                t = new Thread(new ThreadedHandler(session));
                t.start();
            }

} catch (Exception e) {
    System.err.println(e.getMessage());
}
}
}

Upvotes: 0

Views: 1404

Answers (2)

Marcin Kacperek
Marcin Kacperek

Reputation: 89

Use Executor, to create thread pool, and delegate thread executing to that pool. Even if one thread throws an exception, the others will be still active. You can add "unhandledExceptionHandler" to Executor, where you can log every exceptions.

First Executor usage example from google

Upvotes: 1

khachik
khachik

Reputation: 28693

I would recommend to put while body inside a try/catch block, since any error there breaks the loop.

About the NPE - seems that you initialize BufferedReader in;, PrintWriter out; inside the handleSession method, in try. If something fails before is has initialized in and/or out, it will fail with NPE, since shutdown called in finally and closes in and out.

The code as it posted here doesn't break the main loop around accept on NPE in the run of the handler thread.

Upvotes: 1

Related Questions