使用非阻塞ServerSocketChannel、SocketChannel代替ServerSocket和Socket

来源:互联网 发布:黄子华 知乎 编辑:程序博客网 时间:2024/05/18 16:56

           ByteBuffer bytebuf = ByteBuffer.allocate(2048); // 创建一个指定大小的缓冲区
            bytebuf.order(ByteOrder.BIG_ENDIAN); //按照LITTLE_ENDIAN字节序收发数据BIG_ENDIAN
            InetSocketAddress isa = new InetSocketAddress("192.168.0.2",7910);
            SocketChannel sc = SocketChannel.open(); // 建立一个socket通道
            Charset charset = Charset.forName("GBK"); // ???为对等方的编码名,java必须支持。
            CharsetDecoder decoder = charset.newDecoder();
            CharsetEncoder encoder = charset.newEncoder();
            
            sc.connect( isa);  // 建立一个socket连接
            //System.out.println("收到的数据:"+bytebuf.toString());
            sc.read(bytebuf); // 程序到此又走不下去了,一直等待,直到socket自动关闭
            CharBuffer charbuf = decoder.decode(bytebuf);
            System.out.println("收到的数据:"+charbuf);


在使用传统的ServerSocket和Socket的时候 很多时候程序是会阻塞的

比如 serversocket.accept() , socket.getInputStream().read() 的时候都会阻塞 accept()方法除非等到客户端socket的连接或者被异常中断 否则会一直等待下去
read()方法也是如此 除非在输入流中有了足够的数据 否则该方法也会一直等待下去知道数据的到来.在ServerSocket与Socket的方式中 服务器端往往要为每一个客户端(socket)分配一个线程,而每一个线程都有可能处于长时间的阻塞状态中.而过多的线程也会影响服务器的性能.在JDK1.4引入了非阻塞的通信方式,这样使得服务器端只需要一个线程就能处理所有客户端socket的请求.
下面是几个需要用到的核心类
ServerSocketChannel: ServerSocket 的替代类, 支持阻塞通信与非阻塞通信.
SocketChannel: Socket 的替代类, 支持阻塞通信与非阻塞通信.
Selector: 为ServerSocketChannel 监控接收客户端连接就绪事件, 为 SocketChannel 监控连接服务器就绪, 读就绪和写就绪事件.
SelectionKey: 代表 ServerSocketChannel 及 SocketChannel 向 Selector 注册事件的句柄. 当一个 SelectionKey 对象位于Selector 对象的 selected-keys 集合中时, 就表示与这个 SelectionKey 对象相关的事件发生了.在SelectionKey 类中有几个静态常量
SelectionKey.OP_ACCEPT       ->客户端连接就绪事件 等于监听serversocket.accept()返回一个socket
SelectionKey.OP_CONNECT   ->准备连接服务器就绪          跟上面类似,只不过是对于socket的 相当于监听了 socket.connect()
SelectionKey.OP_READ            ->读就绪事件,  表示输入流中已经有了可读数据, 可以执行读操作了
SelectionKey.OP_WRITE          ->写就绪事件
 
下面是服务器端:
Selector selector = Selector.open();         //静态方法 实例化selector
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);  //设置为非阻塞方式,如果为true 那么就为传统的阻塞方式
serverChannel.socket().bind(new InetSocketAddress(port));  //绑定IP 及 端口
serverChannel.register(selector, SelectionKey.OP_ACCEPT); //注册 OP_ACCEPT事件
new ServerThread().start(); //开启一个线程 处理所有请求
ServerThread中的run方法


public void run()  
  {  
   while(true)  
   {  
    try  
    {  
     selector.select();  
     Set<SelectionKey> keys = selector.selectedKeys();  
     Iterator<SelectionKey> iter = keys.iterator();  
     SocketChannel sc ;  
     while(iter.hasNext())  
     {  
      SelectionKey key = iter.next();  
      if(key.isAcceptable());  // 新的连接  
       else if(key.isReadable()) ;// 可读       
       iter.remove(); //处理完事件的要从keys中删去        
     }  
    catch (Exception e)  
    {  
     e.printStackTrace();  
    }  
   }  
  } 




其中在 isAcceptable()中 通过        ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel  sc = ssc.accept(); 得到客户端的SocketChannel
在isReadable()中SocketChannel   sc = (SocketChannel) key.channel(); 得到SocketChannel . 
在SocketChannel 对象中可以用write() read() 进行读写操作 只不过操作的对象不再是byte[] String之类 而是ByteBuffer
 
客户端基本一样
  selector = Selector.open();
  channel = SocketChannel.open(new InetSocketAddress(port));
  channel.configureBlocking(false);
  channel.register(selector,SelectionKey.OP_CONNECT);
  new ClientThread().start();
run方法
    while (true)
    {
     selector.select();
     Set<SelectionKey> keys = selector.selectedKeys();
     Iterator<SelectionKey> iter = keys.iterator();
     while(iter.hasNext())
     {
      SelectionKey key = iter.next();
      if(key.isConnectable());//连接成功&正常
      else  if(key.isReadable())//可读
      iter.remove();
    }
可以通过key.channel();方法得到当前的socketchannel对象
 
总结 其实这里将阻塞变为非阻塞实际是用一个while死循环来处理的
首先通过seleector.select()重新得到事件 只要有事件无论是什么 都交给循环体去处理 在循环体中分别进行不同的处理
而多个socket通过一个seleector进行同意管理
while(一直等待, 直到有接收连接就绪事件, 读就绪事件或写就绪事件发生){             //阻塞
              if(有客户连接)
                   接收客户的连接;                                                    //非阻塞
              if(某个 Socket 的输入流中有可读数据)
                   从输入流中读数据;                                                 //非阻塞
              if(某个 Socket 的输出流可以写数据)
                   向输出流写数据;                                                    //非阻塞
       }
类似这样  以上处理流程采用了轮询的工作方式, 当某一种操作就绪时, 就执行该操作, 否则就查看是否还有其他就绪的操作可以执行. 线程不会因为某一个操作还没有就绪, 就进入阻塞状态, 一直傻傻地在那里等待这个操作就绪. 


Java NIO非阻塞服务器示例
package com.vista.Server;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;


public class SelectorServer 
{
    private static int DEFAULT_SERVERPORT = 6018;//默认端口
    private static int DEFAULT_BUFFERSIZE = 1024;//默认缓冲区大小为1024字节
    private ServerSocketChannel channel;
    private LinkedList<SocketChannel> clients;
    private Selector readSelector;
    private ByteBuffer buffer;//字节缓冲区
    private int port;
    
    public SelectorServer(int port) throws IOException
    {
        this.port = port;
        this.clients = new LinkedList<SocketChannel>();
        this.channel = null;
        this.readSelector = Selector.open();//打开选择器
        this.buffer = ByteBuffer.allocate(DEFAULT_BUFFERSIZE);
    }
     // 服务器程序在服务循环中调用sericeClients()方法为已接受的客户服务
    public void serviceClients()throws IOException
    {
        Set keys;
        Iterator it;
        SelectionKey key;
        SocketChannel client;
        // 在readSelector上调用select()方法,参数1代表如果调用select的时候 那么阻塞最多1秒钟等待可用的客户端连接
        if(readSelector.select(1) > 0)
        {
            keys = readSelector.selectedKeys(); // 取得代表端通道的键集合
            it = keys.iterator();
           // 遍历,为每一个客户服务 
            while(it.hasNext()) 
            {
               key = (SelectionKey)it.next();
               if(key.isReadable())
               { // 如果通道可读,那么读此通道到buffer中
                  int bytes;
                  client = (SocketChannel)key.channel();// 取得键对应的通道
                  buffer.clear(); // 清空缓冲区中的内容,设置好position,limit,准备接受数据
                  bytes = client.read(buffer); // 从通道中读数据到缓冲中,返回读取得字节数
                  if(bytes >= 0) 
                  {
                     buffer.flip(); // 准备将缓冲中的数据写回到通道中
                     client.write(buffer);  // 数据写回到通道中
                  } 
                  else if(bytes < 0) 
                  { // 如果返回小于零的值代表读到了流的末尾
                     clients.remove(client);
                  // 通道关闭时,选择键也被取消
                     client.close();
                  }
               }
            }
         }
    }
    
    public void registerClient(SocketChannel client) throws IOException
    {// 配置和注册代表客户连接的通道对象
        client.configureBlocking(false);  // 设置此通道使用非阻塞模式    
        client.register(readSelector, SelectionKey.OP_READ); // 将这个通道注册到选择器上
        clients.add(client); //保存这个通道对象
    }
    public void listen() throws IOException
    { //服务器开始监听端口,提供服务
        ServerSocket socket;
        SocketChannel client;
        channel = ServerSocketChannel.open(); // 打开通道
        socket = channel.socket();   //得到与通到相关的socket对象
        socket.bind(new InetSocketAddress(port), 10);   //将scoket榜定在制定的端口上
        //配置通到使用非阻塞模式,在非阻塞模式下,可以编写多道程序同时避免使用复杂的多线程
        channel.configureBlocking(false);    
        try 
        {
            while(true) 
            {//     与通常的程序不同,这里使用channel.accpet()接受客户端连接请求,而不是在socket对象上调用accept(),这里在调用accept()方法时如果通道配置为非阻塞模式,那么accept()方法立即返回null,并不阻塞
                client = channel.accept();    
                if(client != null)
                {
                    registerClient(client); // 注册客户信息
                }
                serviceClients();  // 为以连接的客户服务
            }
        } 
        finally 
        {
            socket.close(); // 关闭socket,关闭socket会同时关闭与此socket关联的通道
        }
    }
    public static void main(String[] args) throws IOException 
    {
        System.out.println("服务器启动");
        SelectorServer server = new SelectorServer(SelectorServer.DEFAULT_SERVERPORT);
        server.listen(); //服务器开始监听端口,提供服务


        
    }


}


修改版本:
package com.vista.Server;


import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;


public class SelectorServer 
{
    private static int DEFAULT_SERVERPORT = 6018;//默认端口
    private static int DEFAULT_BUFFERSIZE = 1024;//默认缓冲区大小为1024字节
    private static String DEFAULT_CHARSET = "GB2312";//默认码集
    private static String DEFAULT_FILENAME = "bigfile.dat";
    private ServerSocketChannel channel;
    private LinkedList<SocketChannel> clients;
    private Selector selector;//选择器
    private ByteBuffer buffer;//字节缓冲区
    private int port;
    private Charset charset;//字符集
    private CharsetDecoder decoder;//解码器
    
    
    public SelectorServer(int port) throws IOException
    {
        this.port = port;
        this.clients = new LinkedList<SocketChannel>();
        this.channel = null;
        this.selector = Selector.open();//打开选择器
        this.buffer = ByteBuffer.allocate(DEFAULT_BUFFERSIZE);
        this.charset = Charset.forName(DEFAULT_CHARSET);
        this.decoder = this.charset.newDecoder();
        
    }
    
     private class HandleClient 
     {
         private String strGreeting = "welcome to VistaQQ";
         public HandleClient() throws IOException 
         {
         }
         public String readBlock() 
         {//读块数据
             return this.strGreeting;
         }
         public void close() 
         {
             
         }
    }


    protected void handleKey(SelectionKey key) throws IOException
    {//处理事件
          if (key.isAcceptable()) 
          { // 接收请求
              ServerSocketChannel server = (ServerSocketChannel) key.channel();//取出对应的服务器通道
              SocketChannel channel = server.accept();
              channel.configureBlocking(false);
              channel.register(selector, SelectionKey.OP_READ);//客户socket通道注册读操作
          }
          else if (key.isReadable()) 
          { // 读信息
              SocketChannel channel = (SocketChannel) key.channel();
              int count = channel.read(this.buffer);
              if (count > 0) 
              {
                this.buffer.flip();
                CharBuffer charBuffer = decoder.decode(this.buffer);
                System.out.println("Client >>" + charBuffer.toString());
                SelectionKey wKey = channel.register(selector,
                    SelectionKey.OP_WRITE);//为客户sockt通道注册写操作
                wKey.attach(new HandleClient());
              } 
              else
              {//客户已经断开
                channel.close();
              }
              this.buffer.clear();//清空缓冲区
         }
         else if (key.isWritable()) 
         { // 写事件
              SocketChannel channel = (SocketChannel) key.channel();
              HandleClient handle = (HandleClient) key.attachment();//取出处理者
              ByteBuffer block = ByteBuffer.wrap(handle.readBlock().getBytes());
              channel.write(block);
             // channel.socket().getInputStream().(block);
//              PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
//                        channel.socket().getOutputStream())), true);
//              out.write(block.toString());


        }


    }
    public void listen() throws IOException
    { //服务器开始监听端口,提供服务
        ServerSocket socket;
        channel = ServerSocketChannel.open(); // 打开通道
        socket = channel.socket();   //得到与通到相关的socket对象
        socket.bind(new InetSocketAddress(port));   //将scoket榜定在制定的端口上
        //配置通到使用非阻塞模式,在非阻塞模式下,可以编写多道程序同时避免使用复杂的多线程
        channel.configureBlocking(false);    
        channel.register(selector, SelectionKey.OP_ACCEPT);
        try 
        {
            while(true) 
            {//     与通常的程序不同,这里使用channel.accpet()接受客户端连接请求,而不是在socket对象上调用accept(),这里在调用accept()方法时如果通道配置为非阻塞模式,那么accept()方法立即返回null,并不阻塞
                this.selector.select();
                Iterator iter = this.selector.selectedKeys().iterator();
                while(iter.hasNext())
                {
                    SelectionKey key = (SelectionKey)iter.next();
                    iter.remove();
                    this.handleKey(key);
                    
                }
            }
        } 
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException 
    {
        System.out.println("服务器启动");
        SelectorServer server = new SelectorServer(SelectorServer.DEFAULT_SERVERPORT);
        server.listen(); //服务器开始监听端口,提供服务
    }


}

原创粉丝点击