1

I have an InputStream and an OutputStream to a server. I can send a bunch of JSON requests over the wire and get a stream of responses back from this server. From this, I'd like to build a wrapper that provides getters like getFoo() that create a request, send it, and get a response.

I'm not sure how to handle this considering I may have many clients using this single InputStream and OutputStream at a given time, and am hoping there's a good way to design this.

Here's one option I considered:

  • InputStream reader constantly reads responses, and puts them in a Map<RequestType, Response> that stores the latest Response for each RequestType (where requestType is getFoo, getBar, etc)
  • When I call getFoo() on my wrapper, it writes the request to OutputStream, and then sits waiting for responseMap.get(RequestType.FOO), reads it, and deletes that entry in the map.

Another option:

  • When I call getFoo() on my wrapper, it registers itself as a callback with the InputStream reader
  • When the InputStream reader parses a response (e.g. the foo response from above) it notifies all listeners waiting for foo response, then clears the listeners.

Both of these seem fragile when I start thinking about concurrency. Is there a better way to approach this?

  • Is it impossible to add a (synchronizedly) unique identifier for each request? There are multiple threads/processes that might write requests to the OutputStream and read from the Map at the same time? – SOFe Jul 29 '16 at 7:54
  • Yes, I can add a unique ID to requests so I can match up a response with a request. I feel confident I can match up a response to a request, just not sure how to notify the caller. – Crummy Jul 29 '16 at 7:55
  • Is your server handling continuous connections, such as an IRC connection (where the responses aren't one-time like HTTP)? In that way, what is wrong with concurrency in the second option? – SOFe Jul 29 '16 at 8:03
  • I was concerned about adding and removing callbacks while other clients are making calls but that shouldn't be an issue with a unique ID. I have a bit more confidence now, I'll start working on the second proposal, thanks. – Crummy Jul 29 '16 at 8:08
2

I have an InputStream and an OutputStream to a server. I can send a bunch of JSON requests over the wire and get a stream of responses back from this server

Can you not just open multiple connections to the server, and hence get multiple input/output streams ? In that scenario you can assert that the component opening that connection will only get the responses meant for it, and it alone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.