繁体   English   中英

ObjectInputStream和ObjectOutputStream

[英]ObjectInputStream and ObjectOutputStream

我已经编写了一个EchoServer,如果已经相应发送了数据,则使用String ack进行响应。

我的客户端看起来像这样...为了从服务器接收确认应答,“ echoSocket”将接收到的数据放入我的ObjectInputStream中。 仅当我注释掉这些部分后,客户端才能正常工作

        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();

        }

有人知道为什么它不发送我的字符串吗?

谢谢,马吕斯

实际上,不建议通过套接字使用对象流。 您可能会考虑使用完整的Web服务或RMI。

如果您读入缓冲区并在尝试对对象流进行反序列化之前确保已拥有全部业务,则可能会更好。

为什么不使用粗麻布图书馆?

它的工作原理就像一种魅力: http : //karussell.wordpress.com/2009/04/10/hessian-web-service-protocol-hello-world-example/

或尝试春季远程处理(不是那么轻量级)

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

看起来客户端正在尝试在写入消息之前读取确认。

将“发送”和“接收”代码分成单独的线程,编写器线程可以写入套接字,而您的其他线程在调用readObject()被阻塞。

如果这将是一个长期运行的客户端,我还建议使用较低级别的DataInputStream和DataOutputStream而不是ObjectInputStream / ObjectOutputStream,以防止保留可能很大的对象IdentityHashmap。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM