SocketException:socket在ServerSocket上的accept()中关闭

时间:2016-07-17 08:48:25

标签: java multithreading sockets port

我写了一个小代码,我试图在特定端口上侦听如下(只是尝试一些东西):

public class Test {

    public static class MyThread extends Thread {
        ServerSocket ss = null;
        public MyThread(int port){
            try {
                ss = new ServerSocket(port);
            } catch (IOException e) {
                System.out.println("Exception in assigning port : " + port);
                e.printStackTrace();
            }
        }
        public void stopListening(){
            try {
                ss.close();
            } catch (IOException e) {
                System.out.println("Exception in closing socket : " + ss.getLocalPort());
                e.printStackTrace();
            }
        }
        public void run(){
            try {
                ss.accept();
            } catch (IOException e) {
                System.out.println("Exception in listening on port : " + ss.getLocalPort());
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        List<MyThread> threadList = new LinkedList<>();
        for (int i = 50000; i < 50005; i++) {
            MyThread thread = new MyThread(i);
            threadList.add(thread);
            thread.start();
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e2) {
            e2.printStackTrace();
        }
        for (MyThread myThread : threadList) {
            myThread.stopListening();
        }
    }
}

但我无法启动一个单独的线程,因为我不断获得ss.accept()

  

侦听端口时出现异常:

我在每种情况下都得到以下异常:

java.net.SocketException: socket closed
    at java.net.DualStackPlainSocketImpl.accept0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketAccept(Unknown Source)
    at java.net.AbstractPlainSocketImpl.accept(Unknown Source)
    at java.net.PlainSocketImpl.accept(Unknown Source)
    at java.net.ServerSocket.implAccept(Unknown Source)
    at java.net.ServerSocket.accept(Unknown Source)
    at com.harman.hlacssmdw.Test$MyThread.run(Test.java:40)

我使用netstat -anp检查了50000到50000的端口,没有任何主题被占用。

我无法理解我做错了什么,请帮助!!!

1 个答案:

答案 0 :(得分:4)

ServerSocket已关闭,因为您通过调用stopListening()来关闭它。这导致等待该ServerSocket的accept()的所有线程的异常。