I'm currently studying NIO in order of implementing a custom client server protocol, and I get confused about NIO usage.
As far as I undestood from material I've read, NIO is intrinsically a non-blocking and, as a consequence, an asynchronous way to execute request on (and read response from) a remote server. Looking at most of the example I've found on the web, the general idea behind server-side NIO programming may be summarized as follows:
- create a single I/O worker thread, which reads in a non-blocking way as many data as possibile from each requests;
- all read data must be incapsulated in a "message" or "request" - so that there must be a mean to identify a "complete" request;
- all requests are queued and processed by "worker threads" which produce "responses";
- responses are sent back to clients using the I/O worker thread.
I don't know if I understood well this model, anyway I haven't had big troubles in figuring out how it works. Instead, I'm really confused on how I should develop my client, since most examples I've found use an asynchronous approach even on client side. Normally I need to send a request and wait for a response in a blocking way: a common scenario is GUI's usage in which user execute a request and must wait untill server sends back a response. It seems that I cannot mix blocking IO on client and non blocking IO on server.
So, I tried to mix up things using this approach: I wrote a sendRequest method which:
- uses client's opened channel to write the request;
- the actual read on client's channel is performed by an Handler, which runs in a separate thread; both sendRequest and Handler share a Lock object
- sendRequest writes request to the server and suspend on the lock;
- sendRequest must be notified by Handler thread when response has arrived, and only then may return.
In a nutshell this client design works specularly as server design does, with the difference that the calling thread is actually blocked until response is ready.
I'm asking your help to verify how much I'm far away to a solid understanding on how a NIO server-client should work....
Thanks in advance !
Hey, check out my mega multi devastator cannon. It's wicked. It makes this tiny ad look weak: