Android中的异步IO-Select模型

1 介绍:
在进入手机开发之前,一直是做服务器开发的,所以对网络这部分相对比较熟悉,而在传统简单的网络系统里面,都是单线程,Server->Client的交互,而实际应用中,多数是需要异步处理的。对应到操作系统层面,如Windows的IOCP模型,Linux的Epoll模型,FreeBSD的kqueue模型。在三个操作系统层面,有一个通用的select模型,Java里面实现的也是select异步模型。

2 相关类和知识:

Channels This class provides several utilities to get I/O streams from channels.
DatagramChannel A DatagramChannel is a selectable channel that represents a partial abstraction of a datagram socket.
FileChannel An abstract channel type for interaction with a platform file.
FileChannel.MapMode MapMode defines file mapping mode constants.
FileLock A FileLock represents a locked region of a file.
Pipe A pipe contains two channels, forming a unidirectional pipe.
Pipe.SinkChannel Writable sink channel used to write to a pipe.
Pipe.SourceChannel Readable source channel used to read from a pipe.
SelectableChannel A channel that can be used with a Selector.
SelectionKey A SelectionKey represents the relationship between a channel and a selector for which the channel is registered.
Selector A controller for the selection of SelectableChannel objects.
ServerSocketChannel A ServerSocketChannel is a partial abstraction of a selectable, stream-oriented listening socket.
SocketChannel A SocketChannel is a selectable channel that provides a partial abstraction of stream connecting socket.

主要的参考类为:

SelectionKey,Selector,ServerSocketChannel,SocketChannel,SelectableChannel,ByteBuffer

3 代码结构:
本模型代码含两部分,客户端和服务器端。
客户端的代码为简单的Activity + Thread组成。
服务器端代码相对复杂一点,由Activity + Thread + Interface + InterfaceImpl组成。

客户端主要代码:

package com.jouhu.asynclient;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;


import android.os.Handler;
import android.os.Message;

public class TCPClientReadThread implements Runnable {

    private Selector selector;
   
    private Handler handler;
     
    public TCPClientReadThread(Selector selector,Handler handler){
        this.selector=selector;
        this.handler = handler;
        new Thread(this).start();
      }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            while (selector.select() > 0) {
                // 遍历每个有可用IO操作Channel对应的SelectionKey
                for (SelectionKey sk : selector.selectedKeys()) {
                    // 如果该SelectionKey对应的Channel中有可读的数据
                    if (sk.isReadable()) {
                        // 使用NIO读取Channel中的数据
                        SocketChannel sc = (SocketChannel) sk.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        buffer.flip();
                   
                        // 将字节转化为为UTF-16的字符串  
                        String receivedString=Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
                        Message msg = handler.obtainMessage(AndroidAsynClient.RECV_DATA);
                        msg.obj = "接收到来自服务器"+sc.socket().getRemoteSocketAddress()+"的信息:"+receivedString;
                        msg.sendToTarget();
                        // 控制台打印出来
                        //System.out.println("接收到来自服务器"+sc.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
                   
                        // 为下一次读取作准备
                        sk.interestOps(SelectionKey.OP_READ);
                    }
                  // 删除正在处理的SelectionKey
                  selector.selectedKeys().remove(sk);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }  
    }
}


服务器端代码主要代码组成:

package com.jouhu.asynserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;


import android.os.Handler;
import android.os.Message;

public class AsynServerThread extends Thread {
   
   
    private Handler handler = null;
    private int port;
    private Selector selector = null;
    private ServerSocketChannel listenerChannel = null;
   
    private TCPProtocol protocol;
    private static final int BufferSize=1024;
    private static final int TimeOut=3000;
   
    public AsynServerThread(Handler handler,int port)
    {
        this.handler = handler;
        this.port = port;
        try {
            selector = Selector.open();
            // 打开监听信道
            listenerChannel=ServerSocketChannel.open();
            // 与本地端口绑定
            listenerChannel.socket().bind(new InetSocketAddress(port));
            // 设置为非阻塞模式
            listenerChannel.configureBlocking(false);
            // 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作
            listenerChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 创建一个处理协议的实现类,由它来具体操作
        protocol=new TCPProtocolImpl(BufferSize,handler);
    }
   
    public void run()
    {
        while(true){
            // 等待某信道就绪(或超时)
            int iselect = 0;
            try {
                iselect = selector.select(TimeOut);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(iselect==0){
                //System.out.print("独自等待.");
                continue;
            }
            // 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
            Iterator<SelectionKey> keyIter=selector.selectedKeys().iterator();
            while(keyIter.hasNext()){
                SelectionKey key=keyIter.next();
                try{
                    if(key.isAcceptable()){
                        // 有客户端连接请求时
                        protocol.handleAccept(key);
                        Message msg = handler.obtainMessage(AndroidAsynServer.CLIENT_COME);
                        msg.obj = "Accept";
                        msg.sendToTarget();
                    }
             
                    if(key.isReadable()){
                        // 从客户端读取数据
                        protocol.handleRead(key);
                        Message msg = handler.obtainMessage(AndroidAsynServer.RECV_DATA);
                        msg.obj = "RECV Data";
                        msg.sendToTarget();
                    }
             
                    if(key.isValid() && key.isWritable()){
                        // 客户端可写时
                        protocol.handleWrite(key);
                        Message msg = handler.obtainMessage(AndroidAsynServer.SEND_DATA);
                        msg.obj = "Send Data";
                        msg.sendToTarget();
                    }
                }
                catch(IOException ex){
                    // 出现IO异常(如客户端断开连接)时移除处理过的键
                    keyIter.remove();
                    continue;
                }
                // 移除处理过的键
                keyIter.remove();

            }
        }
    }
}


其中TCP协议处理实现代码:

package com.jouhu.asynserver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.sql.Date;

import android.os.Handler;
import android.os.Message;

public final class TCPProtocolImpl implements TCPProtocol {
   
    private int bufferSize;
    private Handler handler = null;
   
    public TCPProtocolImpl(int bufferSize,Handler handler){
        this.bufferSize=bufferSize;
        this.handler = handler;
    }

    @Override
    public void handleAccept(SelectionKey key) throws IOException {
        // TODO Auto-generated method stub
        SocketChannel clientChannel=((ServerSocketChannel)key.channel()).accept();
        clientChannel.configureBlocking(false);
        clientChannel.register(key.selector(), SelectionKey.OP_READ,ByteBuffer.allocate(bufferSize));
    }

    @Override
    public void handleRead(SelectionKey key) throws IOException {
        // TODO Auto-generated method stub
        // 获得与客户端通信的信道
        SocketChannel clientChannel=(SocketChannel)key.channel();
       
        // 得到并清空缓冲区
        ByteBuffer buffer=(ByteBuffer)key.attachment();
        buffer.clear();
       
        // 读取信息获得读取的字节数
        long bytesRead=clientChannel.read(buffer);
       
        if(bytesRead==-1){
          // 没有读取到内容的情况
          clientChannel.close();
        }
        else{
          // 将缓冲区准备为数据传出状态
          buffer.flip();
         
          // 将字节转化为为UTF-8的字符串  
          String receivedString=Charset.forName("UTF-8").newDecoder().decode(buffer).toString();
         
          Message msg = handler.obtainMessage(AndroidAsynServer.CLIENT_COME);
          msg.obj = receivedString;
          msg.sendToTarget();
         
          // 控制台打印出来
          //System.out.println("接收到来自"+clientChannel.socket().getRemoteSocketAddress()+"的信息:"+receivedString);
         
          // 准备发送的文本
         
          String sendString="你好,客户端. @已经收到你的信息"+receivedString;
          buffer=ByteBuffer.wrap(sendString.getBytes("UTF-8"));
          clientChannel.write(buffer);
         
          // 设置为下一次读取或是写入做准备
          key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
        }
    }

    @Override
    public void handleWrite(SelectionKey key) throws IOException {
        String sendString = "Just a Test";
        // TODO Auto-generated method stub
        SocketChannel clientChannel=(SocketChannel)key.channel();
        ByteBuffer buffer=(ByteBuffer)key.attachment();
        buffer=ByteBuffer.wrap(sendString.getBytes("UTF-8"));
        clientChannel.write(buffer);
        // 设置为下一次读取或是写入做准备
        key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
    }

}


4 代码下载:
客户端:
AndroidAsynClient
服务器端:
AndroidAsynServer

图:

Android异步Socket服务器端

Android异步客户端

5 后记:

本文代码参考了likwo兄转载的文章,其为java中的实现,我结合了Handler的特性,移植到了Android中来。希望可以起到抛砖引玉的作用。在这里感谢作者的代码。代码在三星I809和HTC G18上测试过,没有问题,但是商业应用还需修改。

6 主参考文章:
1 http://www.cnblogs.com/likwo/archive/2010/06/29/1767814.html

7 参考文章:
1 http://hi.baidu.com/gk14/blog/item/a27b50e7e791f222b9382081.html
2 https://developer.android.com/reference/java/nio/channels/SelectionKey.html
3 http://docs.oracle.com/javase/1.4.2/docs/api/java/nio/channels/SocketChannel.html
4 http://stackoverflow.com/questions/7450758/selector-on-android-sockets-behaves-strangely
5 https://developer.android.com/reference/java/nio/channels/Selector.html
6 http://android-drwable.googlecode.com/svn-history/r9/trunk/AndroidUI/bin/com/example/TestApp/AstCommClient.java.bak
7 http://www.android123.com.cn/androidkaifa/697.html
8 http://www.java2s.com/Open-Source/Android/android-core/platform-libcore/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java.htm
9 http://www.blogjava.net/longturi/archive/2010/02/03/311820.html
10 http://developer.android.com/reference/java/nio/channels/package-summary.html
11 http://www.android123.com.cn/androidkaifa/695.html
12 http://stackoverflow.com/questions/4081594/socketchannel-is-not-ready
13 http://stackoverflow.com/questions/2685534/java-serversocketchannel-socketchannel-callback
14 http://blog.csdn.net/ureygo/article/details/7098213

-END-


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值