JAVA NIO Socket通道
发布日期:2021-05-09 05:38:09 浏览次数:1917 分类:博客文章

本文共 15293 字,大约阅读时间需要 50 分钟。

 

DatagramChannel���SocketChannel������������������������������ServerSocketChannel������������������������������������������������������������SocketChannel���������������������������

Socket������������������������������������������������socket���������������������������socket���������������������������������getChannel()���������

��������� SelectableChannel���������socket������������������������������������

 

Readiness Selection���������������������������������������������������������������������������������������������������������������������������...������������������������������������������������������������������������������������������������������������������������������������IO���������������������������������������������������

Selector������������������������������������������������������������Java���������������������������������������������������������������������������������

Selector��������������������������������������������������������������������������������������������������������������������������������������������������������������������������� 

���������������������������������������������������������������������������������������������������

SelectionKey���������������������������������������������������������������������SelectableChannel.register()���������������������������������������������������

���������������������������������������������������noblocking������������������������

 

chanel.register(selector, keystate)���������������������������

selector.select()���������������������������������channel���keystate���������

selectionKey.cancel()������������������������ 

������������������������������������������������������������������������������������������������������������������������������������������������������������������

selectionkey������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������interest������������������������������������interestOps()���������������������������������������������������������������������interestOps()������������������������������������������������

readyOpts()������������������������������������������ready���������interest���������������������������������������select()���������������������������������������

if((key.readOps() & SelctionKey.OP_READ) != 0){

    buffer.clear();

    key.channel().read(buffer);

    do()....

}

���������������attach()

SelectionKey key = SelectableChannel.register(Selector, SelectionKey.OP_XXX, paramObj);

���������

SelectionKey key = SelectableChannel.register(Selector, SelectionKey.OP_XXX);

key.attach(paramObj);

SelectionKey ������������������������������

������������

Selector���������������������������������������������������null���keys()������������������������

���������������������selectedKeys()������������������������������������������������������

������������������������������select()���poll()���epoll()������������������native call������������������������������������������������������������������������������������������������������

  1. ������������������������������������������������������������������������������������������������������������������������������������������������������������������������

  2. ������������������������������interest������������������������������������������������������������������������������������������������������������������������������������������������������������������������

    ������������������������������������

    a. ���������������������������������������������������������������reay���������������������������������������������������������������������

    b. ���������������������������������������������������������ready������������������������������������������������������

  3. select������������������������select()������������������������������������������������������������������������������������������������������������������������������������������

������������������������������������������������������������������������������������������������������������������������������������������

���������������select: select()��� select(timeout)���selectNow()���������������������������������������������

������ Selector ��������� wakeup( )��������������������������������������������������������������������������������������������������������������������������������������������� select( )������������������������������������������������������������������������������������������������������������������������ wakeup( )������������������������������������������������������������������������������������������������������������������������������������������������������������������������

������������������������������������������������������ wakeup( )��������������� selectNow( )������������������������������ 

��������������������������������������������� select ������(������������������������������������)��������������� selectKeys( )������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ Iterator��������������� remove( )��������������������������������������������������������������������� select( )������������������������������������

package org.windwant.nio;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.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * Created by windwant on 2016/10/27. */public class SocketChannelOpt {    private static final String HOST = "localhost";    private static final int PORT = 8888;    private static ExecutorService read = Executors.newFixedThreadPool(5);    private static ExecutorService write = Executors.newFixedThreadPool(5);    public static void main(String[] args){        ServerSocketChannel serverSocketChannel = null;        ServerSocket serverSocket = null;        Selector selector = null;        try {            serverSocketChannel = ServerSocketChannel.open();//������������������ServerSocketChannel            serverSocket = serverSocketChannel.socket(); //������channel���������ServerSocket            serverSocket.bind(new InetSocketAddress(HOST, PORT)); //������������            serverSocketChannel.configureBlocking(false); //������ServerSocketChannel���������������            selector = Selector.open();//������������������Selector            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//���������������������������������������������������            while (true){//������������                if(selector.select() == 0){//���������������������������������������������������������                    continue;                }                Iterator
it = selector.selectedKeys().iterator(); //������������������������������ while (it.hasNext()){ SelectionKey selectionKey = it.next(); //������������������ if (selectionKey.isAcceptable()){ ServerSocketChannel schannel = (ServerSocketChannel) selectionKey.channel();//������������������������������������������������������������ SocketChannel socketChannel = schannel.accept();//���������������������������������socket������ if(null == socketChannel){ continue; } socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); //��������������������������������������������������� }else if(selectionKey.isReadable()){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); ByteBuffer byteBuffer = ByteBuffer.allocate(4*1024); StringBuilder result = new StringBuilder(); while (socketChannel.read(byteBuffer) > 0){//������������ byteBuffer.flip(); result.append(new String(byteBuffer.array())); byteBuffer.clear();//������������ ������������flip() } System.out.println("server receive: " + result.toString()); socketChannel.register(selector, SelectionKey.OP_WRITE); }else if(selectionKey.isWritable()){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); String sendStr = "server send data: " + Math.random(); ByteBuffer send = ByteBuffer.wrap(sendStr.getBytes()); while (send.hasRemaining()){ socketChannel.write(send); } socketChannel.register(selector, SelectionKey.OP_READ); System.out.println(sendStr); } it.remove(); } } } catch (IOException e) { e.printStackTrace(); } }}

 

Selector���������������������������������

������������������������������������������������������������������������������������������������������������������������������������������������������������������������

package org.windwant.nio;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.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * ��������������������������� * Created by windwant on 2016/10/27. */public class TSocketChannelOpt {    private static final String HOST = "localhost";    private static final int PORT = 8888;    private static ExecutorService read = Executors.newFixedThreadPool(5);    private static ExecutorService write = Executors.newFixedThreadPool(5);    public static void main(String[] args){        ServerSocketChannel serverSocketChannel = null;        ServerSocket serverSocket = null;        Selector selector = null;        try {            serverSocketChannel = ServerSocketChannel.open();//������������������ServerSocketChannel            serverSocket = serverSocketChannel.socket(); //������channel���������ServerSocket            serverSocket.bind(new InetSocketAddress(HOST, PORT)); //������������            serverSocketChannel.configureBlocking(false); //������ServerSocketChannel���������������            selector = Selector.open();//������������������Selector            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//���������������������������������������������������            while (true){//������������                if(selector.select() == 0){//���������������������������������������������������������                    continue;                }                Iterator
it = selector.selectedKeys().iterator(); //������������������������������ while (it.hasNext()){ SelectionKey selectionKey = it.next(); it.remove(); //������������������ if (selectionKey.isAcceptable()){ ServerSocketChannel schannel = (ServerSocketChannel) selectionKey.channel();//������������������������������������������������������������ SocketChannel socketChannel = schannel.accept();//���������������������������������socket������ if(null == socketChannel){ continue; } socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); //��������������������������������������������������� }else if(selectionKey.isReadable()){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); read.execute(new MyReadRunnable(socketChannel));// SocketChannel socketChannel = (SocketChannel) selectionKey.channel();// ByteBuffer byteBuffer = ByteBuffer.allocate(4*1024);//// StringBuilder result = new StringBuilder();// while (socketChannel.read(byteBuffer) > 0){//������������// byteBuffer.flip();// result.append(new String(byteBuffer.array()));// byteBuffer.clear();//������������ ������������flip()// }//// System.out.println("server receive: " + result.toString()); socketChannel.register(selector, SelectionKey.OP_WRITE); }else if(selectionKey.isWritable()){ SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); write.execute(new MyWriteRunnable(socketChannel));// String sendStr = "server send data: " + Math.random();// ByteBuffer send = ByteBuffer.wrap(sendStr.getBytes());// while (send.hasRemaining()){// socketChannel.write(send);// }// System.out.println(sendStr); socketChannel.register(selector, SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); } } static class MyReadRunnable implements Runnable { private SocketChannel channel; public MyReadRunnable(SocketChannel channel){ this.channel = channel; } @Override public synchronized void run() { ByteBuffer byteBuffer = ByteBuffer.allocate(4*1024); StringBuilder result = new StringBuilder(); try { while (channel.read(byteBuffer) > 0){//������������ byteBuffer.flip(); result.append(new String(byteBuffer.array())); byteBuffer.clear();//������������ ������������flip() } System.out.println("server receive: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } } } static class MyWriteRunnable implements Runnable { private SocketChannel channel; public MyWriteRunnable(SocketChannel channel){ this.channel = channel; } @Override public void run() { String sendStr = "server send data: " + Math.random(); ByteBuffer send = ByteBuffer.wrap(sendStr.getBytes()); try { while (send.hasRemaining()) { channel.write(send); } System.out.println(sendStr); }catch (Exception e){ e.printStackTrace(); } } }}
 
上一篇:Spring 资源文件处理
下一篇:JAVA NIO FileChannel 内存映射文件

发表评论

最新留言

不错!
[***.144.177.141]2025年04月08日 20时22分12秒