套接字 DataOutputStream writeInt() 方法 NullPointerException

Socket DataOutputStream writeInt() method NullPointerException

我正在尝试在服务器端发送序列化 class 对象。首先我在字节数组中序列化对象,然后我获取数组长度并将长度作为整数发送并在服务器端发送数组。但是程序在堆栈跟踪中使用 NullPointerException 折叠。所有 class 字段都是静态的。什么问题?

public class Main {

public static int port = 8085;
public static String address = "127.0.0.1";
public static Socket clientSocket;
public static InputStream in;
public static OutputStream out;
public static DataInputStream din;
public static DataOutputStream dout;
public static boolean stop = false;
public static int l;

public Main(){
    try {
        InetAddress ipAddress = InetAddress.getByName(address);
        clientSocket = new Socket(ipAddress, port);
        in = clientSocket.getInputStream();
        out = clientSocket.getOutputStream();
        din = new DataInputStream(in);
        dout = new DataOutputStream(out);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args){
    int number = 5;
    String str = "Hello world!";
    byte[] bt = str.getBytes();
    ArrayList<Byte> array = new ArrayList<Byte>();
    for(int i=0; i<bt.length; i++){
        array.add(bt[i]);
    }
    while(!stop){
        Template protocol = new Template(number, str, array);
        byte[] serializeObject = SerializationUtils.serialize(protocol);
        l = serializeObject.length;
        try {
            dout.writeInt(l); //NPE
            dout.write(serializeObject); //NPE
            dout.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

}

您正在调用静态字段 dout 而未对其进行初始化。默认情况下,Java 个对象引用被初始化为 null。初始化这些字段的代码在构造函数中,它不会被调用,因为您在静态 main() 方法中,它没有绑定到实例。所以你的引用仍然是 null,因此当你调用你的 dout.writeInt(l); 时是 NullPointerException

除非您显式创建一个 Main() 实例,如 Main myMain = new Main();,您的主要方法需要初始化您的 dout 引用,因为它是 null.

由于这看起来更像是一个简单的通信测试,只需将构造函数中的初始化代码移至您的 main 方法即可。