socket.getInputStream()中的ObjectInputStream [英] ObjectInputStream from socket.getInputStream()

查看:1285
本文介绍了socket.getInputStream()中的ObjectInputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有服务器

ServerSocket socketListener = new ServerSocket(Config.PORT);
...
client = socketListener.accept();

和客户

sock = new Socket("127.0.0.1", Config.PORT);

我想使用ObjectInputStream和ObjectOutputStream在它们之间传输一些序列化数据。
当我尝试做的时候

I want to transfer between them some serialized data using ObjectInputStream and ObjectOutputStream. When I try to do

ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

服务器端和客户端都没有任何事情发生。一切都落在那条线上。客户端和服务器都试图从套接字获取输入流,但它既不起作用,也不起作用,也不起作用。
如何解决这个问题,以便我可以在客户端和服务器之间传递序列化数据?

Nothing happens neither on the server side nor client side. Everything falls on that line. Both the client and the server is trying to get the input stream from the socket, but it does not work nor the client nor the server. How do I solve this problem so that I can pass the serialized data between client and server?

推荐答案

As < a href =http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html#ObjectInputStream%28java.io.InputStream%29 =nofollow> javadoc 说:


创建一个从指定的InputStream读取的ObjectInputStream。从流中读取序列化流头并进行验证。此构造函数将阻塞,直到相应的ObjectOutputStream已写入并刷新标头。

Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.

因此,因为服务器和客户端都是通过打开来启动的一个InputStream,你实现了一个死锁:它们都阻塞,直到另一方发送了流头。如果从客户端打开ObjectInputStream开始,则必须首先在服务器端打开ObjectOutputStream(并在必要时立即刷新)(反之亦然)。

So, since both the server and the client start by opening an InputStream, you implemented a deadlock: they both block until the other party has sent the stream header. If you start by opening an ObjectInputStream at client side, you must start by opening an ObjectOutputStream (and flushing immediately if necessary) at server-side (or vice-versa).

这篇关于socket.getInputStream()中的ObjectInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆