开发者

ObjectInputStream and ObjectOutputStream

开发者 https://www.devze.com 2022-12-12 19:05 出处:网络
I have written an EchoServer that responds with the String ack if the data have been send accordingly.

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


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号