SocketException: socket closed in accept() on ServerSocket

I had written a small code where I am trying to listen on particular port as follows (just trying out something) :

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();
        }
    }
}

But I am unable to start even a single thread , for every ss.accept() I keep getting :

Exception in listening on port :

I get the following exception in each case :

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)

I checked the ports from 50000 to 50000 using netstat -anp , none of theme are occupied.

I am unable to understand what am I doing wrong, Please help !!!

Upvotes: 1

Views: 3655

Answers (1)

k5_
k5_

Reputation: 5568

The ServerSocket is closed because you close it by calling stopListening(). That leads to an Exception for all Threads waiting on accept() of that ServerSocket.

Upvotes: 4

Related Questions