Java——NIO-BIO-AIO

使用nio作为服务端


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class TestNio {
    private ByteBuffer readBuffer;
    private Selector selector;

    /**
     * 初始化
     *
     */
    private void init() {
        readBuffer = ByteBuffer.allocate(1024);
        ServerSocketChannel servSocketChannel;
        try {
            // 获得一个ServerSocket通道
            servSocketChannel = ServerSocketChannel.open();
            // 设置通道为非阻
            servSocketChannel.configureBlocking(false);
            // 将该通道对应的ServerSocket绑定到port端口
            servSocketChannel.socket().bind(new InetSocketAddress(8888));
            // 获得一个通道管理器
            selector = Selector.open();
            //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
            //当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
            servSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     */
    private void listen() {
        System.out.println("启动成功。。。");
        // 轮询访问selector
        while (true) {
            try {
                selector.select();
                Iterator ite = selector.selectedKeys().iterator();
                while (ite.hasNext()) {
                    SelectionKey key = (SelectionKey) ite.next();
                    ite.remove();
                    handleKey(key);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
    private void handleKey(SelectionKey key) throws IOException {
        SocketChannel channel = null;
        try {
            if (key.isAcceptable()) {
                ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                channel = serverChannel.accept();
                channel.configureBlocking(false);
                channel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                channel = (SocketChannel) key.channel();
                readBuffer.clear();
                int count = channel.read(readBuffer);
                if (count > 0) {
                    readBuffer.flip();
                    ByteBuffer response = ByteBuffer.wrap(new byte[] { 'r','e', 's', 'p', 'o', 'n', 's', 'e' });
                    byte[] request=new byte[7];
                    System.out.println(readBuffer.get(request));
                    while (response.hasRemaining()) {
                        channel.write(response);
                    }
                } else {
                    channel.close();
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
            if (channel != null) {
                channel.close();
            }
        }
    }
    public static void main(String[] args) {
        TestNio nioServer = new TestNio();
        nioServer.init();
        nioServer.listen();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值