0

I'm trying to send serialize class object on the server side. First I serialize object in byte array, then I take array length and send lenght as integer and send array on the srever side. But programm fold with NullPointerException in stacktrace. All class-fields is static. What a problem?

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

}

}

Denis Makovsky
  • 460
  • 7
  • 22

1 Answers1

0

You're invoking the static field dout without it being initialized. By default, Java object references are initialized to null. The code that initializes those fields is in the constructor, which is not being called since you're inside the static main() method, which is not tied to an instance. So your reference is still null, hence the NullPointerException when you invoke your dout.writeInt(l);.

Unless you explicitly create a Main() instance, as in Main myMain = new Main();, your main method needs to initialize your dout reference, since it's null.

Since this seems more like a simple communication test, just move the initialization code in the constructor to your main method.

fsb
  • 111
  • 1
  • 5