Java – Cannot get ObjectInputStream to work

javanetwork-programmingsocketsstream

I am currently trying to get my server to create a connection with a client. I have created a thread for each connection but the server is currently not creating the Input Stream. I have tested this by printing out numbers but only 1 and 2 get printed out. Im sure this is just a small problem that im missing.

public class ObjectHandler implements Runnable{
    Socket sock;
    ObjectInputStream ois;
    ObjectOutputStream oops;
    InputStream is;


    public ObjectHandler(Socket clientSocket) throws IOException {
        System.out.println("1");
        sock = clientSocket;

        is = sock.getInputStream();
        System.out.println("2");
        ois = new ObjectInputStream(new BufferedInputStream(is));
        System.out.println("3");

        OutputStream os = sock.getOutputStream();

        oops = new ObjectOutputStream(new BufferedOutputStream(os));
        outputSockets.add(oops);    

    }

I have now removed the throws IOException and surrounded the reader with a try catch. After the client has crashed it now prints this error:

at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ThreadPool$ObjectHandler.<init>(ThreadPool.java:95)
at ThreadPool.addThread(ThreadPool.java:31)
at ObjectServerTest.go(ObjectServerTest.java:93)
at ObjectServerTest.main(ObjectServerTest.java:124)

Best Solution

When constructing Object streams over sockets, you always need to construct the output stream first and flush it before creating the input stream (due to how the streams are implemented).