2

Class c extends thread

static Queue<Socket> socketQueue
Make connection to another server or client
And then add socket to socketqueue

Class a extends thread

method a
bufferedinputstream bis = socketQueue.poll
Do work
Make bis null without closing it<br>

Class b extends thread

Method b
Bufferedinputstream bis = socketqueue.poll
Do work
Make bis null without closing it

I did make bufferedinput stream null since i do not want to close the connected socket. Several posts were telling me that closing input/output stream would close the socket as well. Whenever I use input/output stream with socket, I usually close stream and socket if its not null.

What I am trying to do here is to make the socket alive and reuse when input or output stream is needed without connecting again.

I tried socket.shutdowninput and output, however, this throws an exception when i make another input/output stream with the socket.

Is there anything I have misunderstood or am missing at this point?

Gray
  • 112,334
  • 22
  • 281
  • 349
handicop
  • 800
  • 11
  • 22

1 Answers1

9

A connection over a socket only ever has one InputStream and one OutputStream. As soon as you close any of those (or the Socket itself) the connection is automatically closed. You need to store the streams you need somewhere and use those, you can not get them from the same Socket each time you need them.

Bombe
  • 78,266
  • 20
  • 120
  • 125
  • Thanks for the answer. So there's no way i can make multiple streams with a single connected socket while freely closing one of them and still using the others. – handicop Jan 11 '12 at 22:30
  • Right. As said, you need to store the strems somewhere and use them from there; a usual approach is to just use the stored streams whenever you need them. That might be impractical in a multi-threaded scenario but in this case even with multiple streams writing to the same socket you have to take great care to not simply break everything. :) – Bombe Jan 12 '12 at 08:04
  • 1
    You can indeed get them from the socket every time you need them. – user207421 Feb 25 '16 at 22:14