问题描述
状况:客户端通过一个单一的插座连接到服务器通信。客户可以随机发送序列化对象,或者只是简单的参数,则该服务器。
Situation : A client communicates to a server via a single socket connection. The Client can randomly send serialized objects, or just simple parameters, the the server.
问题:如何让服务器同时为ObjectInputStream中的InputStream和从客户听
Problem : How to make the server simultaneously listen for ObjectInputStream and InputStream from the Client ?
我在想什么的: A'主人'的线程派生2子线程。一个孩子侦听从客户机到ObjectInputStreams,另一子监听InputStreams
What I'm thinking of: A 'master' thread spawns 2 child Threads. One child listens to ObjectInputStreams from the client, and the other child listens to InputStreams.
请问这种方法工作?因为我听说ObjectInputStream的阻止。什么线程安全?同步问题?
Will this approach work ? Because I've heard ObjectInputStream is blocking. What about thread safety ? Synchronization issues ?
推荐答案
的ObjectInputStream
有也很喜欢方法的readFully(字节[] buf中)
,所以没有必要使用的InputStream
ObjectInputStream
has also methods like readFully(byte[] buf)
, so there is no need to use InputStream.
然后,如果你在一个InputStream打开一个ObjectInputStream的,你可以不使用任何的InputStream多,为了不打破的ObjectInputStream的功能。
Then, if you open an ObjectInputStream on an InputStream, you may not use that InputStream any more, in order not to break functionality of ObjectInputStream.
附
ObjectInputStream的是InputStream的一个子类,所以你可以调用一个ObjectInputStream的实例InputStream的所有方法,但不能同时使用。所以,你有发展的时候连接用作ObjectInputStream的和为InputStream的当其中prescribes的协议。如果一方通过InputStream的接口发送消息和其它来自ObjectInputStream中(反之亦然)读取它,错误是不可避免的。
ObjectInputStream is a subclass of InputStream, so you can call all methods of InputStream on an ObjectInputStream instance, but not simultaneously. So you have to develop a protocol which prescribes when connection is used as ObjectInputStream and when as InputStream. If one side sends message via InputStream interface and the other reads it from ObjectInputStream (or vice versa), an error is inevitable.
这篇关于安卓:2个线程监听同一插座上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!