I'm coding a server/client application pair in Java, as I learn about it. I have basic functionality of sending a message to the server and parsing it but in thinking about the big picture of their communication, I'm stumped about where to go from here.
Both the client and the server have to be able to initiate an exchange of data so I need to have one thread reading at each side, at all times. On top of that, when one initiates an exchange, it needs to listen for the reply. If I do that, though, I'd have two threads reading data, which I guess wouldn't end well since, from my understanding, I wouldn't be able to make sure the data gets read in the thread I want.
I see a few options but I'm not confident at going too far with each solution since my knowledge doesn't let me think too far ahead.
Use only the first thread that was originally waiting for data before the exchange, to also read the reply for the query that was just sent by a different thread, and forward the data where it belongs.
This sounds difficult. If I read the data in the same thread that requested it, it would be very straightforward compared to this.
Start reading the InputStream in the same thread that requested data and make the thread that was originally listening, wait.
My problem with this is that, if there's other data arriving by the same client that is unrelated with the query that was just made, it would be fetched by this thread instead of the other one, which kinda defeats the purpose of reading the data here.
Establish another connection from the client, to another port, after the first is established. Then I could use one socket for exchanges initiated by the other side, and the other to listen for replies of queries made in the meantime.
This way I'd know exactly what is going where, but wouldn't I have this same problem further down the road if I have two queries waiting for data at the same time?
This sounds like simple functionality, trivial to find in many applications, so I'm guessing there's some tried and true method out there and there's no reason for me to try and reinvent the wheel here.
So, to sum it up, what's the recommended way to set up client/server applications that can cope with possibly overlapping dialogs, initiated by either one, at unpredictable times?
I started to modify some parts of the question to make it a bit clearer but I ended up almost rewriting it completely. If it's still a bit confusing is because I am confused. I think I'm missing some simple point but I haven't been able to find examples that show this.