java nio测试

package com.java.nio.study;

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.Set;

public class NioServer {
    
    // 选择器
    private Selector selector;

    private ByteBuffer byteBuffer=ByteBuffer.allocate(2014);
    
    //nio服务端
    public NioServer(int port) throws Exception {
        selector=Selector.open(); // 打开一个选择器 选择器能够监听是否有感兴趣的事情发生
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        ServerSocket serverSocket=serverSocketChannel.socket();
        InetSocketAddress inetSocketAddress=new InetSocketAddress(port);
        serverSocket.bind(inetSocketAddress);
        serverSocketChannel.configureBlocking(false); // 非阻塞
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 注册感兴趣的事件
        System.out.println("--server --- start----");
    }
   
    // 启动nio服务的监听处理
    public void start() throws Exception {
        while(true) { //  
            int selects=selector.select(); // 没有敢兴趣的事件 阻塞 --》有那么selects > 0
            if(selects <= 0) {
                continue;
            }
           Set<SelectionKey> selectionKeys=selector.selectedKeys(); // 获取已经选择器集合
           Iterator<SelectionKey> it=selectionKeys.iterator();
           while(it.hasNext()) {
                SelectionKey selectionKey=it.next();
                handle(selectionKey); //处理 ,路由操作
                it.remove();
            }

        }
    }

    private void handle(SelectionKey selectionKey) throws Exception {
        if(selectionKey.isAcceptable()) { // 已经准备了Accept
            ServerSocketChannel serverSocketChannel=(ServerSocketChannel)selectionKey.channel();
            SocketChannel socketChannel=serverSocketChannel.accept(); // accept这个socket
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ); // 注册read感兴趣事件
            System.out.println("---- register read-----");

        } else if(selectionKey.isReadable()) {
            System.out.println("----- is read----");
            readBuffer(selectionKey);
        } else if(selectionKey.isWritable()) {
            System.out.println("------ is write-----");
            SocketChannel socketChannel=(SocketChannel)selectionKey.channel();
            byteBuffer.clear();
            byteBuffer.put("hello ljq--".getBytes());
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            System.out.println("--write to client --");

        }
    }

    private void readBuffer(SelectionKey selectionKey) throws Exception {
        SocketChannel socketChannel=(SocketChannel)selectionKey.channel();
        int size=socketChannel.read(byteBuffer);
        if(size > 0) {
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_WRITE);
            byteBuffer.clear();
        } else {
            socketChannel.close();
        }
    }

    public static void main(String[] args) {
        try {
            NioServer nioServer=new NioServer(9999);
            nioServer.start();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}

 

 

package com.java.nio.study;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class NioClient extends Thread {

    private Socket socket;

    private PrintWriter out;

    private InputStream input;

    public NioClient(int port) throws Exception {
        socket=new Socket();
        socket.connect(new InetSocketAddress(port));
        out=new PrintWriter(socket.getOutputStream());
        input=socket.getInputStream();
    }

    @Override
    public void run() {
        while(true) {
            try {
                Thread.sleep(3000);
                System.out.println("-------run---------");
                out.print("---send to nio server--");
                out.flush();
                int size=input.available();
                if(size > 0) {
                    byte[] bytes=new byte[size];
                    input.read(bytes);
                    System.out.println("reive = " + new String(bytes));
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            NioClient client=new NioClient(9999);
            client.start();
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值