Android: 2 threads listening on the same socket

早过忘川 提交于 2019-12-25 02:53:55

问题


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.

Problem : How to make the server simultaneously listen for ObjectInputStream and InputStream from the Client ?

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.

Will this approach work ? Because I've heard ObjectInputStream is blocking. What about thread safety ? Synchronization issues ?


回答1:


ObjectInputStream has also methods like readFully(byte[] buf), so there is no need to use InputStream.

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.

APPENDED

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.



来源:https://stackoverflow.com/questions/21190296/android-2-threads-listening-on-the-same-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!