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