Java7 AIO Starter instance, the first is the server-side implementation:
Service-side code
Simpleserver:
Java code
- Public class Simpleserver {
- Public simpleserver (int port) throws IOException {
- final Asynchronousserversocketchannel listener = Asynchronousserversocketchannel.open (). Bind (New Inetsocketaddress (port));
- Listener.accept (null, new Completionhandler<asynchronoussocketchannel, void> () {
- public void completed (Asynchronoussocketchannel ch, void att) {
- //Accept Next Connection
- Listener.accept (null, this );
- //Handle Current connection
- Handle (CH);
- }
- public void failed (Throwable exc, void att) {
- }
- });
- }
- public void handle (Asynchronoussocketchannel ch) {
- Bytebuffer Bytebuffer = bytebuffer.allocate (32);
- try {
- Ch.read (Bytebuffer). get ();
- } catch (Interruptedexception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- } catch (Executionexception e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- Bytebuffer.flip ();
- System.out.println (Bytebuffer.get ());
- //Do something
- }
- }
followed by the client implementation: client code
SimpleClient:
Java code
- Public class SimpleClient {
- private Asynchronoussocketchannel client;
- Public simpleclient (String host, int port) throws IOException, Interruptedexception, executionexception {
- this.client = Asynchronoussocketchannel.open ();
- future<?> future = Client.connect (new Inetsocketaddress (host, port));
- Future.get ();
- }
- public void write (byte b) {
- Bytebuffer Bytebuffer = bytebuffer.allocate (32);
- Bytebuffer.put (b);
- Bytebuffer.flip ();
- Client.write (Bytebuffer);
- }
- }
Write a simple test case to run the server and the client, running TestServer () first, running TestClient ();
Test Cases
Aiotest
Java code
- Public class Aiotest {
- @Test
- public void TestServer () throws IOException, interruptedexception {
- Simpleserver Server = new Simpleserver (7788);
- Thread.Sleep (10000);
- }
- @Test
- public void TestClient () throws IOException, Interruptedexception, executionexception {
- SimpleClient client = new SimpleClient ("localhost", 7788);
- Client.write ((byte) 11);
- }
- }
Because it is asynchronous, there is no synchronization blocking when running the server, where I add a thread sleep (), if not, the program will run out of garbage.
http://tigerlchen.iteye.com/blog/1747221
Java AIO Getting Started instance (GO)