Hey everyone, I am getting a null pointer exception (I will highlight the location after the code is shown). I am trying to extend a class that is a server:
import java.io.IOException; import java.io.*; import java.net.*; public class MultiChatServer extends MultiEchoServer{ static private ServerSocket serverSocket; static private Socket connection; //serversocket instanciation public MultiChatServer(int port) throws IOException{ super(port); //create a list to store all the the connections } public static void main(String args[])throws IOException{ new MultiChatServer(4433);//construct a serversocket while(true){ //STEP2: Do a blocking listen to the established server socket //when a new connection occurs, the accept method will trigger and and another thread will be instantiated connection = serverSocket.accept(); System.out.println("New client requesting to connect on connection "+ (connection.getInetAddress().getHostName())); HandlerThread newThread = new HandlerThread(connection); //pass connection to be threaded System.out.println("Started a new thread for new client"); newThread.start(); //envokes run method } //serverSocket.close(); } }
The line
connection = serverSocket.accept();
causes the nullPointerException.
Just to be complete, here is the class i am extending:
import java.io.*; import java.net.*; public class MultiEchoServer{ //Initialise variables static private ServerSocket serverSocket = null; static private Socket connection = null; //constructor public MultiEchoServer(int port) throws IOException{ try{ System.out.println("Server waiting for a client to connect on port 4433" ); serverSocket = new ServerSocket(port); }catch(IOException e){ System.err.println("Could not listen on port: 4433"); System.exit(1); } } //end constructor public static void main(String args[])throws IOException{ new MultiEchoServer(4433); while(true){ connection = serverSocket.accept(); System.out.println("New client requesting to connect on connection "+ (connection.getInetAddress().getHostName())); HandlerThread newThread = new HandlerThread(connection); System.out.println("Started a new thread for new client"); newThread.start(); } //serverSocket.close(); } }
All I am trying to do is be in a position to have the same functionality as the superclass. I want to redefine the while loop in the main in the subclass.