javasocketsstream-socket-client

many io stream from one socket


Can I parallelly connect many independent I/O streams of server's socket and client's socket such that each pair of I/O streams could send different data at the same time ?

How could I achieve such a connection in java without increasing number of sockets between server and client?


Solution

  • There's always one stream for input and one stream for output, so you can't add more streams.

    However, as sje397 commented, you can use the same stream to send "different" data, you just need to come up with a way to distinguish the channels in the receiving side, so it can reconstruct the data properly. This is a protocol design issue.

    Edit: In your example you could have a packet structure with a header that tells the type (or channel) of the packet, length of the data and for the file packets some additional information if needed. Let's assume that the length field is a single byte, so your maximum packet size (for String packets) would be 1 + 1 + 255 = 257 bytes.

    When the server reads bytes, it will check the first byte for the type of the packet. After determining that it's a String packet, it will read the length, then read the payload. Then the process repeats itself.

    For file data additional header information is most likely needed, otherwise the non-String packets will just be a bunch of bytes.

    This means that your protocol will become packet based, so you must write the data one packet at a time. Assuming that a data packet has a max size of 64K, you would then be able to send data in the following way (imagine that it's a network pipe):

    Client -> 257(S) -> 64K(D) -> 257(S) -> 64K(D) -> 257(S) -> Server allowing you to interleave the two different kinds of data in a single network connection.