wishi
wishi

Reputation: 7387

ObjectInputStream and ObjectOutputStream

I have written an EchoServer that responds with the String ack if the data have been send accordingly.

My client looks like this... In order to receive the ack answer from the server the "echoSocket" puts the received data into in, my ObjectInputStream. Only if I comment these parts out the client works

        echoSocket = new Socket(server_name, tcp_port);
        System.out.println(" *** Connected to " + server_name  + " ***");
        System.out.println("Press Enter to send your message.");

        out = new ObjectOutputStream(echoSocket.getOutputStream());
        in = new ObjectInputStream(echoSocket.getInputStream());

        out.flush();

        String message = System.console().readLine();

        while(!message.equals("quit")) {


            // problem                
            if (in.readObject().equals(ack)) 
                System.out.println("ACKed");
            in.close();
            // problem ends
            out.flush();

            out.writeObject(message);
            System.out.println("Sending: " + message);      
            message = System.console().readLine();
            out.flush();

        }

Does anybody know why it won't send my Strings?

Thanks, Marius

Upvotes: 1

Views: 1722

Answers (4)

Sam Barnum
Sam Barnum

Reputation: 10714

Split the "sending" and "receiving" code into separate threads, the writer thread can write to the socket while your other thread is blocked on the call to readObject().

If this is going to be a long-running client, I'd also recommend using the lower-level DataInputStream and DataOutputStream instead of ObjectInputStream / ObjectOutputStream, to prevent holding onto a possibly large IdentityHashmap of the objects.

Upvotes: 1

Karussell
Karussell

Reputation: 17375

Why not use hessian library?

It works like a charm: http://karussell.wordpress.com/2009/04/10/hessian-web-service-protocol-hello-world-example/

Or try spring remoting (which is not that lightweight)

http://static.springsource.org/spring/docs/2.5.x/reference/remoting.html

Upvotes: 2

Stephen C
Stephen C

Reputation: 718708

It looks like the client is trying to read the acknowledgement before it has written the message.

Upvotes: 1

bmargulies
bmargulies

Reputation: 100013

Using object streams over sockets is not really a recommended idea. You might consider a full web service, or RMI.

It might work better if you read into a buffer and make sure that you have the whole business before trying to deserialize with the object streams.

Upvotes: 3

Related Questions