Java AIO 应用实例

项目地址:https://github.com/windwant/aio-test

  • Server:

     1 package org.windwant.aio;
     2
     3 import java.io.IOException;
     4 import java.net.InetSocketAddress;
     5 import java.nio.ByteBuffer;
     6 import java.nio.channels.AsynchronousChannelGroup;
     7 import java.nio.channels.AsynchronousServerSocketChannel;
     8 import java.nio.channels.AsynchronousSocketChannel;
     9 import java.nio.channels.CompletionHandler;
    10 import java.nio.charset.Charset;
    11 import java.util.concurrent.ExecutionException;
    12 import java.util.concurrent.Executors;
    13
    14 /**
    15  * AsynchronousServerSocketChannel
    16  */
    17 public class AIOServer implements Runnable{
    18
    19     private int port = 8889;
    20     private int threadSize = 10;
    21     protected AsynchronousChannelGroup asynchronousChannelGroup;
    22
    23     protected AsynchronousServerSocketChannel serverChannel;
    24
    25     public AIOServer(int port, int threadSize) {
    26         this.port = port;
    27         this.threadSize = threadSize;
    28     }
    29
    30     public static void main(String[] args) throws IOException {
    31         new Thread(new AIOServer(8989, 19)).start();
    32     }
    33
    34     public void run() {
    35         try{
    36             asynchronousChannelGroup = AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10);
    37             serverChannel = AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
    38             serverChannel.bind(new InetSocketAddress(port));
    39             System.out.println("listening on port: " + port);
    40             serverChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel, AIOServer>() {
    41                 final ByteBuffer echoBuffer = ByteBuffer.allocateDirect(1024);
    42
    43                 public void completed(AsynchronousSocketChannel result, AIOServer attachment) {
    44                     System.out.println("reading begin...");
    45                     try {
    46                         System.out.println("远程地址:" + result.getRemoteAddress());
    47                         echoBuffer.clear();
    48                         result.read(echoBuffer).get();
    49                         echoBuffer.flip();
    50                         System.out.println("received : " + Charset.defaultCharset().decode(echoBuffer));
    51                         String msg = "server test msg-" + Math.random();
    52                         System.out.println("server send data: " + msg);
    53                         result.write(ByteBuffer.wrap(msg.getBytes()));
    54                     } catch (IOException e) {
    55                         e.printStackTrace();
    56                     } catch (InterruptedException e) {
    57                         e.printStackTrace();
    58                     } catch (ExecutionException e) {
    59                         e.printStackTrace();
    60                     } finally {
    61                         attachment.serverChannel.accept(attachment, this);// 监听新的请求,递归调用。
    62                     }
    63
    64                 }
    65
    66                 public void failed(Throwable exc, AIOServer attachment) {
    67                     System.out.println("received failed");
    68                     exc.printStackTrace();
    69                     attachment.serverChannel.accept(attachment, this);
    70                 }
    71             });
    72             System.in.read();
    73
    74         }catch (Exception e){
    75             e.printStackTrace();
    76         }
    77     }
    78 }
  • Client:
     1 package org.windwant.aio;
     2
     3 import java.io.IOException;
     4 import java.net.InetSocketAddress;
     5 import java.nio.ByteBuffer;
     6 import java.nio.channels.AsynchronousSocketChannel;
     7 import java.nio.channels.CompletionHandler;
     8
     9 /**
    10  * AsynchronousSocketChannel
    11  */
    12 public class AIOClient implements Runnable{
    13
    14     private AsynchronousSocketChannel client;
    15     private String host;
    16     private int port;
    17     public AIOClient(String host, int port) throws IOException {
    18         this.client = AsynchronousSocketChannel.open();
    19         this.host = host;
    20         this.port = port;
    21     }
    22
    23     public static void main(String[] args) {
    24         try {
    25             new Thread(new AIOClient("127.0.0.1", 8989)).start();
    26             System.in.read();
    27         } catch (IOException e) {
    28             e.printStackTrace();
    29         }
    30
    31     }
    32
    33     public void run() {
    34         client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Object>() {
    35             public void completed(Void result, Object attachment) {
    36                     String msg = "client test msg-" + Math.random();
    37                     client.write(ByteBuffer.wrap(msg.getBytes()));
    38                     System.out.println("client send data:" + msg);
    39             }
    40
    41             public void failed(Throwable exc, Object attachment) {
    42                 System.out.println("client send field...");
    43             }
    44         });
    45
    46         final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    47         client.read(byteBuffer, this, new CompletionHandler<Integer, Object>() {
    48             public void completed(Integer result, Object attachment) {
    49                 System.out.println(result);
    50                 System.out.println("client read data: " + new String(byteBuffer.array()));
    51             }
    52
    53             public void failed(Throwable exc, Object attachment) {
    54                 System.out.println("read faield");
    55             }
    56         });
    57     }
    58 }
时间: 2024-10-18 21:28:45

Java AIO 应用实例的相关文章

Java AIO 入门实例(转)

Java7 AIO入门实例,首先是服务端实现: 服务端代码 SimpleServer: Java代码   public class SimpleServer { public SimpleServer(int port) throws IOException { final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(por

java 调用mysql实例

java 调用mysql实例: package com.tanglei.test1; import java.sql.*; public class Testsql{ public static void main(String []args){ Mysql mysql=new Mysql(); } } class Mysql{ // MySQL的JDBC URL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称?参数=值 // 避免中文乱码要指定useUnicode和char

Java内存溢出实例总结

java虚拟机规范规定的java虚拟机内存其实就是java虚拟机运行时数据区,其架构如下: <img width="492" height="325" src="file:///C:/Users/zpy/AppData/Local/Temp/msohtml1/01/clip_image001.jpg" <="" span="">' v:shapes="_x0000_i1029&q

memcached—Java操作Memcached实例

前面博客介绍了如何在Windows操作系统中安装Memcached,总结一下如何使用Java操作Memcached实例: 代码一: package com.ghj.packageoftool; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import jav

Java 类的实例变量初始化的过程 静态块、非静态块、构造函数的加载顺序

Java 类的实例变量初始化的过程 静态块.非静态块.构造函数的加载顺序 先看一道Java面试题: 1 public class Baset { 2 private String baseName = "base"; 3 // 构造方法 4 public Baset() { 5 callName(); 6 } 7 // 成员方法 8 public void callName() { 9 // TODO Auto-generated method stub 10 System.out.p

java操作Hbase实例

所用HBase版本为1.1.2,hadoop版本为2.4 /* * 创建一个students表,并进行相关操作 */ import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apach

java之IO实例

实例1:从键盘接收一个文件夹路径,把文件夹中的所有文件以及文件夹的名字按层级打印 分析:这里用到了file类的方法和递归 public  class  Test10{ public  static  void   main(String[ ]  args) { Scanner  sc=new Scanner(System.in); String  path=sc.nextLine( ); File   f=new  File(path); System.out.println(f.getName

java之登录实例(面向对象,静态,scanner等)

分析:抽取用户类,提取出用户的属性,方法 用户类测试:判断登陆,注册等 User : 用户类    package cn.my.login; import java.util.Scanner; /** *  分析:用户的基本信息 *  用户名,密码,邮箱,电话,地址 *  登录,注册方法 * */public class User { private String username; private String password; private String email; private S

JAVA上百实例源码以及开源项目

简介 笔者当初为了学习JAVA,收集了很多经典源码,源码难易程度分为初级.中级.高级等,详情看源码列表,需要的可以直接下载! 这些源码反映了那时那景笔者对未来的盲目,对代码的热情.执着,对IT的憧憬.向往!此时此景,笔者只专注Android.Iphone等移动平台开发,看着这些源码心中有万分感慨,写此文章纪念那时那景! Java 源码包 Applet钢琴模拟程序java源码 2个目标文件,提供基本的音乐编辑功能.编辑音乐软件的朋友,这款实例会对你有所帮助.Calendar万年历 1个目标文件EJ