Rane
Rane

Reputation: 191

Getting a NullPointerException when I try to write an object to a server in Java

I have a small problem. I have trying to use a method in another class to send an object to the server I have. I am using Java with Sockets.

Method:

public void sendMessageToServer(String message) {

    if (message != null) {
        try {
            serverComManager.outputStream.writeObject(message);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Class trying to use the method:

        sendMessage.sendMessageToServer("Hello");

The error is thrown at the line:

    serverComManager.outputStream.writeObject(message);

Thank you in advance! ~Rane

EDIT: As requested, I have added the 'serverComManager' declaration as well as the code for that class. I have also included the full error. I hope this helps you understand my problem.

Declaration:

    ServerCommunicationManager serverComManager = new ServerCommunicationManager();

Code for ServerCommunicationManager:

boolean connected;


//Setup
Socket clientSocket;
ObjectOutputStream outputStream;
ObjectInputStream inputStream;

public boolean connectToHost() throws UnknownHostException, IOException{


    clientSocket = new Socket("localhost", 2444);
    setupStreams(clientSocket);

    if(clientSocket.isConnected()){
        connected = true;
    }else{
        connected = false;
    }


    return connected;

}

private void setupStreams(Socket s) throws IOException{

    outputStream = new ObjectOutputStream(s.getOutputStream());
    inputStream = new ObjectInputStream(s.getInputStream());

}

Error:

Exception java.lang.NullPointerException
at SendToServer.sendMessageToServer(SendToServer.java:16)
at DissconnectClient.dissconnectFromServer(DissconnectClient.java:15)

Error Lines:

DissconnectClient 15: sendMessage.sendMessageToServer(abortConnectionKeyword);
SendToServer 16: serverComManager.outputStream.writeObject(message);

NOTE: DisconnectClient is one of the classes I am writing with. Here is the class code:

    public class DissconnectClient {

    //Variables
    private final String keyword = "DISSCONNECT";


    //Setup
    SendToServer sendMessage = new SendToServer();


    public void dissconnectFromServer(){

        sendMessage.sendMessageToServer(keyword);

    }

}

Upvotes: 1

Views: 1476

Answers (1)

Marcelo Tataje
Marcelo Tataje

Reputation: 3871

I cannot see where do you assign a value of "serverComManager" or where do you create an isntance of this. Maybe in a constructor method ot the class which has the method "sendMessageToServer" you're doing something like this.serverComManager = (...). I'm not sure how you are handle the logic of "serverComManager" but so far, my approach to solve the issue would be the following (if I'm writing a client that sends a message to the server). And considering there's no code provided for your "serverConnManager", maybe you could identify something missing in your current implementation.

public void sendMessageToServer(String message) {

    if (message != null) {
        try {
            //Assume I already have an instance of client Socket:
            //Socket outgoingConn = new Socket(host, port)
            //1. I get the OutputStream of my outgoing connection
            OutputStream outStream = outgoingConn.getOutputStream();
            //2. Create an object output stream
            ObjectOutputStream objectWriter = new ObjectOutputStream(outStream);
            //3. Write the object
            objectWriter.writeObject(message);
            //Close the io if required (would recommend try-with-resources if using jdk7)
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

If you are working just with String messages, BufferedWriter orBufferedReadr would be enough, if you try to handle complex objects that can be both "beans" or Strings, better if you create something like:

public class MessageBean implements Serializable {
    private MessageType type;
    private Object param;
    //Getters/Setters
}

MessageType could be an enum specifying the type of objects supported, since param field is an object you can handle as an String or as a bean. Then work based on the MessageType or using the "instanceof". But Well, this is just a suggestion if you want to try something further.

Hope it helps. Happy coding!

Regards.

Upvotes: 1

Related Questions