0

So i'm making a server socket I call the constructor to constuct the serversocket then call the getLocalPort method to get the local port but server.getLocalPort(); is throwing a null pointer exception and I can't figure out why i'm stumped. I'm sure its some dumb mistake but I just can't see it.

 public SServer(int port) throws SocketException, IOException 
{
    ServerSocket server = new ServerSocket(port);
    server.setReuseAddress(true);
}
public int getLocalPort() {
    int port = server.getLocalPort();
    return port;
}
Joe
  • 337
  • 2
  • 16
  • You have two different things called `server` in this case - a local variable, and a field. You set the local variable, but not the field. (You probably didn't want to have a local variable at all) – user253751 Feb 28 '15 at 09:10

1 Answers1

1

You initialize a local vairable in your constructor instead of initializing the member of your class. Therefore your server member remains null.

Change

public SServer(int port) throws SocketException, IOException 
{
    ServerSocket server = new ServerSocket(port);
    server.setReuseAddress(true);
}

to

public SServer(int port) throws SocketException, IOException 
{
    server = new ServerSocket(port);
    server.setReuseAddress(true);
}
Eran
  • 387,369
  • 54
  • 702
  • 768