有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javasocket上的NullPointerException

当我尝试创建socket连接时,我得到一个返回NullPointerException,当我尝试在主类上打印socket.isConnected()时,它返回true,但当我尝试在另一个方法上再次打印它时,它返回NullPointerException,这是我的代码

服务器

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

此代码将首先返回true,因为socket。isConnected()正在处理main,但不处理send方法


共 (1) 个答案

  1. # 1 楼答案

    实际上它是NullPointerException,因为 socketConnect从未初始化过,所以必须初始化它,您可以在main方法中使用这些变量,当然您必须将它们声明为 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
    对不起,我的英语不好