退出程序时异常连接重置

时间:2014-05-19 10:07:13

标签: java

我有一个与MySQL连接的多线程服务器,每次运行它都会得到相同的异常:java.net.SocketException:Connection reset 这是我的服务器:      public void run(){       // synchronized(this){

        try {
            serverSocket = new ServerSocket(serverPort);
            System.out.println("Server started on port " + serverPort);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         try{ 
             while(true){ 
                 Socket s = serverSocket.accept();
                 es.execute((Runnable) new WorkerThread(s));
                 }
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
             finally{ 

                     try {
                        serverSocket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                 }

}

这是我的工作线程:

             String[] str = new String[10]; 
         String arr;
            try {
                int i=0;
                int b=0;
                String message=null;

            while(!Thread.currentThread().isInterrupted())   {
             message=in.readLine();

            if (message.equals("exit")){
            System.exit(0); 
            }
                       // .... here I have other if statements 
}

            } catch (IOException | SQLException e1) {

                e1.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                }
            }

和例外:

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at Pack.WorkerThread.run(WorkerThread.java:62)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

它出现在这里:

message=in.readLine();

1 个答案:

答案 0 :(得分:0)

如果使用System.exit(0)退出程序;您的连接将被终止,从而导致此异常。

如果您不希望抛出此异常,请确保在调用System.exit(0)或终止线程之前使用in.close()关闭inputstream。