首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

[转]NIO Client程序片段

2012-10-24 
[转]NIO Client程序片断The clientBefore getting started its worth mentioning that the client implem

[转]NIO Client程序片断
The client

Before getting started it's worth mentioning that the client implementation is going to end up looking a lot like the server implementation we just finished writing. There's going to be a lot of common functionality that can be factored out and shared between the client and server implementation. For the most part I'm going to totally ignore that and write the client as a standalone piece of code to avoid clouding the picture with layer upon layer of abstraction. I'll leave that as an exercise to the reader. However, there are one or two little bits of code we've already written that will be shared between the implementations, because not doing so may reduce clarity. It's a judgement call on my part so if you disagree, forgive me and try not to let it bother you too much.

That said, let's get on with the client code. Once again, we're going to need some infrastructure. We can actually borrow a lot from the server code, since once a connection is accepted/established there's not a lot of difference between a client and server. A client still needs to read and write data, so at the very least we're going to need that logic. Given the similarities I'm going to build the client implementation by starting with the server implementation and tweaking it as needed.

First, let's remove some bits we don't need. The server socket channel can go, we won't be needing that. We can also remove the accept() method and the logic in the run() method that invokes it.

Next we can throw out most of the logic in the initSelector() method. In fact, we only need the first line, leaving us with a method that looks like this.

 public static void main(String[] args) {    try {      NioClient client = new NioClient(InetAddress.getByName("localhost"), 9090);      Thread t = new Thread(client);      t.setDaemon(true);      t.start();      RspHandler handler = new RspHandler();      client.send("Hello World".getBytes(), handler);      handler.waitForResponse();    } catch (Exception e) {      e.printStackTrace();    }  }



The response handler implementation is shown below. I waited until last so that the waitForResponse() would make sense, along with some of the synchronization logic. It's entirely possible to pull this logic into the send() method, effectively making it a synchronous call. But this tutorial is illustrating asynchronous I/O so that seems kind of silly. It's not as silly as it sounds, mind you, since you might want to handle a large number of active connections even if the client is forced to use them one at a time. But this illustrates how to perform the send asynchronously. Everything else is merely details.

Quoted from: http://www.javafaq.nu/java-article1103.html

热点排行