How to read objects sent over objectOutputStream on a socket server in Java

1.5k views Asked by At

I have the send working but the server side wont receive the object sent in the data input stream. The class is serialized and works when sending but I'm not sure why it is not being received by the server.

Here is my code:

Server.ois = new ObjectInputStream(client.getInputStream());
while(Server.ois.available() != 0) {
    try {
        TriangleSend ts = (TriangleSend)Server.ois.readObject();
        send(ts);
        Server.ois.close();
    } catch (Exception e) {
        continue;
    }
}

That is all in a while loop and a try. It also generates the exception when received.

The send (TriangleSend) method is:

public static void send(TriangleSend coords) {
    for (Socket client : Server.clients) {
        try {
            if (client != null) {
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
                    oos.writeObject(coords);
                    oos.flush();
                } catch (Exception e) {}
            }
        } catch (NullPointerException e) {
            continue;
        }
    }
}

EDIT: Source Code And An Exception: http://pastebin.com/rYzqduer

heres the exception:

java.io.StreamCorruptedException: invalid stream header: 73720027
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
    at com.gopro2027.lwjgl.server.ServerThread$1$1.run(ServerThread.java:88)
    at java.lang.Thread.run(Thread.java:745)
Could not send data Timeout: 0
2

There are 2 answers

2
user207421 On
while(Server.ois.available() != 0) {

available() is not a valid test for end of stream. See the Javadoc. You should change the loop to while (true) and break when you catch EOFException.

9
Dave G On

Tyler - wrap your client's output stream with a BufferedOutputStream before constructing the ObjectOutputStream - conversely do a BufferedInputStream before constructing the ObjectInputStream on the server side. That should help with the read/write process.

Server Side:

Server.ois = new ObjectInputStream(new BufferedInputStream(client.getInputStream()));
while(Server.ois.available() != 0) {
    try {
        TriangleSend ts = (TriangleSend)Server.ois.readObject();
        send(ts);
        Server.ois.close();
    } catch (Exception e) {
        e.printStackTrace();
        continue;
    }
}

Send Triangle:

public static void send(TriangleSend coords) {
    for (Socket client : Server.clients) {
        if (client != null) {
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(client.getOutputStream()));
                oos.writeObject(coords);
                oos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

removed edit