-1

i'm getting a return NullPointerException when i try to create a socket connection, when i try to print socket.isConnected() on the main class it return true, but when i try to print it again on the other method, it return NullPointerException, here is my code.

Server

ServerSocket socketServer = null;
Socket socketConnect = null;

public static void main(String[] args) throws IOException {
    ChatServer cc = new ChatServer();
    cc.socketServer = new ServerSocket(2000);
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ChatServer().setVisible(true);
        }
    });
        cc.socketConnect = cc.socketServer.accept();
        System.out.println(cc.socketConnect.isConnected());
}

public void send(String msg) throws IOException {
    System.out.println(this.socketConnect.isConnected());
}

this code will return true first, because the socket.isConnected() is working on the main, but not on the send method

Walls
  • 149
  • 13

1 Answers1

1

In effect it is NullPointerException because socketConnect was never initialized, you must initialize it, you can use these variables in your main method of course you must declare them as static.

// static variable
public static ServerSocket socketServer = null;
public static Socket socketConnect = null;

public static void main(String[] args) throws IOException {
    ChatServer cc = new ChatServer();
    cc.socketServer = new ServerSocket(2000);
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ChatServer().setVisible(true);
        }
    });
    cc.socketConnect = cc.socketServer.accept();
    System.out.println(cc.socketConnect.isConnected());
    
    // instance
    socketServer = cc.socketServer;
    socketConnect = cc.socketConnect;
}

// now you can use socketConnect, cause you did init in main at the final from the main method
public void send(String msg) throws IOException {
    System.out.println(this.socketConnect.isConnected());
}

gl
Sorry my English is not good.

Diego-1743
  • 126
  • 2