javasocketsobjectinputstreamdatainputstreameofexception

Creating ObjectInputStream from Socket throwing EOFException


I will try to put it simply.

Class constructor 'B' is recieving a socket as parameter, it is coming from class 'A'. In A, the socket is used for I/O using DataInputStream and DataOutputStream. Neither the socket nor the streams are been closed by A.

Then, in B i try to create an ObjectInputStream from the same socket but i am getting a null reference in the OIS and the EOFException is been thrown. I have no clue why is this happening. Maybe i cannot reuse the socket with different kind of streams.

I have read many related questions but no one with sockets. Bellow some code.

public HiloLoginHandler(Socket _socket) { // this is class 'A'
    socket = _socket;
        bytesOut = new DataOutputStream(socket.getOutputStream());
        bytesIn = new DataInputStream(socket.getInputStream());

}

public ClientInputHandler(Socket _socket) { // This is Class 'B'
        socket = _socket;

        InputStream is= socket.getInputStream();    
        ObjectInputStream in= new ObjectInputStream(is); // EOFException here
} 

Solution

  • Make up your mind. Using DataOutputStream at one end and ObjectInputStream at the other end will never work. You have to use complementary streams.

    In this case use DataInputStream instead of ObjectInputStream, as obviously no objects will ever be sent.

    Why you are opening an input stream when the peer has already closed the connection is another mystery. If the peer never sends anything why bother?

    i am getting a null reference in the OIS

    No you aren't.