Socket DataOutputStream writeInt()方法NullPointerException

时间:2015-05-25 13:36:48

标签: sockets nullpointerexception dataoutputstream

我试图在服务器端发送序列化类对象。首先我在字节数组中序列化对象,然后我获取数组长度并发送lenght作为整数并在srever端发送数组。但是programm在stacktrace中使用NullPointerException进行折叠。所有类字段都是静态的。怎么了?

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

}

}

1 个答案:

答案 0 :(得分:0)

您正在调用静态字段dout而不进行初始化。默认情况下,Java对象引用初始化为null。初始化这些字段的代码位于构造函数中,由于您位于静态main()方法内部而未被调用,因此该方法与实例无关。因此,当您调用null时,您的引用仍为NullPointerException,因此dout.writeInt(l);

除非您明确创建Main()实例,与Main myMain = new Main();中一样,否则您的主要方法需要初始化您的dout引用,因为它是null

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