0

My program was working fine until i got this following message: "Exception in thread "Thread-0" java.lang.NullPointerException" in the run-method. It's pointing towards the row where i have written "Socket socket = serverSocket.accept();". Why is that and how can i solve it?

    private ServerSocket serverSocket;
    private LinkedList<ClientHandler> handlerList = new LinkedList<ClientHandler>();
    private ArrayList<String> invalidUsernames = new ArrayList<String>();

    public Server(int port) {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.getStackTrace();
        }
        start();
    }

    public void run() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                ClientHandler handler = new ClientHandler(socket);
                handler.start();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {
        new Server(6946);
        System.out.println("Server started");
    }
}
Jacki222
  • 13
  • 3
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) Note that if your constructor throws an exception when trying to create the `ServerSocket`, your code ignores that exception and continues. It's entirely possible in this scenario that this is failing and you're simply not capturing that. In the `catch` block you should log or report the exception in some way. – David Aug 31 '20 at 12:39
  • It seems to work now. Thank you! :) – Jacki222 Aug 31 '20 at 12:59

0 Answers0