nullPointerException while using DataInputStream and DataOutputStream to send and int

99 Views Asked by At

I'm practicing on a simple Client / Server connection. The client is supposed to send an Int to the server, and the server is supposed to print this int. However, the server encounters a NullPointerException and doesn't print the int sent by the client.

Here is my server:

package primitives;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import bytes.Server;

public class DataServer {
private ServerSocket serverSocket;
private static DataInputStream in;

public DataServer(int port) throws IOException {
    serverSocket = new ServerSocket(port);
    System.out.println("Server ready at: " + serverSocket);
    Socket clientSocket = serverSocket.accept();

    System.out.println("New client connection: " + clientSocket);
    in = new DataInputStream(clientSocket.getInputStream());
}

public void close() throws IOException {
    serverSocket.close();
}

public static void main(String[] args) throws IOException {
    Server server = new Server(9000);
    int a = DataServer.in.readInt(); // NullPointerException Here
    System.out.println(a);
    server.close(); 
    System.out.println("closed");
}

}

And my client:

package primitives;

import java.io.IOException;
import java.net.Socket;
import java.io.DataOutputStream;

public class DataClient {
    
private Socket socket;
private DataOutputStream out;

public DataClient(String host, int port) throws IOException {
    socket = new Socket(host, port);
    System.out.println("Socket ready: " + socket);
    out = new DataOutputStream(socket.getOutputStream());
}

public void close() throws IOException {
    socket.close();
}

public static void main(String[] args) throws IOException {
    DataClient client = new DataClient("127.0.0.1", 9000); // use port configured in the server code
    client.out.writeInt(154);
    client.out.flush();
    client.close();
}

}

Thank you for your help. I've been trying to search for solutions but couldn't find any, therefore I am sorry if there is a solution that is easily available or if this question has already been asked.

1

There are 1 best solutions below

0
On

Using a static variable which is instantiated in a constructor seems a bit of a nonsense.

The variable DataInputStream in shouldn't be static and should be accessed through a public method on a DataServer instance like this:

DataServer server = new DataServer(9000);
server.getIn().readInt();

This behaviour ensures that object properties are instantiated before they are used.