java套接字上的nullpointerexception

mefy6pfw  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(318)

这个问题在这里已经有答案了

什么是nullpointerexception,如何修复它(12个答案)
上个月关门了。
当我尝试创建套接字连接时,当我尝试打印时,会得到一个return 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方法上不工作

pgpifvop

pgpifvop1#

实际上是这样 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());
}

德国劳埃德船级社
对不起,我的英语不好。

相关问题