Java NIO之多路复用示例

本文介绍了一个使用Java NIO实现的多路复用器示例,包括服务端和客户端代码。服务端代码展示了如何创建多路复用器、监听端口、处理客户端连接和读写操作。客户端代码则演示了如何发起连接请求并发送消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java NIO之多路复用示例

服务端代码

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

public class MultiplexerTimeServer implements Runnable {


    private Selector selector;
    private ServerSocketChannel servChannel;
    private volatile boolean stop = false;

    /**
    * @Desc 初始化多路复用器,绑定端口
    * @Author HeRong
    * @Date   2020/5/3
    */
    public MultiplexerTimeServer( int port) {
        try {
            //创建Reactor线程多路复用器
            selector = Selector.open();
            //创建socket 通道
            servChannel = ServerSocketChannel.open();
            //设置通道为非阻塞
            servChannel.configureBlocking(false);
            //绑定ip端口,设置最大的请求连接数为1024
            servChannel.socket().bind(new InetSocketAddress(port),1024);
            //注册到多路复用器上,监听accpet事件
            servChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("time server is start on port "+port);
        }catch (IOException e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void stop(){
        this.stop = true;
    }

    @Override
    public void run() {
        while (!stop){
            try{
                //设置获取就绪key的休眠时间,每间隔1秒唤醒一次
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                SelectionKey key ;
                while (iterator.hasNext()){
                    key = iterator.next();
                    iterator.remove();
                    try{
                        handlerKey(key);
                    }catch (Exception e){
                        key.cancel();
                        if (key.channel() != null)
                            key.channel().close();
                    }
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handlerKey(SelectionKey key) throws IOException {
        if (key.isValid()){
            //查看是否是accpet事件
            if (key.isAcceptable()){
                ServerSocketChannel channel = (ServerSocketChannel)key.channel();
                //接受客户端请求,三次握手结束,建立物理连接
                SocketChannel accept = channel.accept();
                //设置非阻塞模式
                accept.configureBlocking(false);
                //注册监听读取事件
                accept.register(selector,SelectionKey.OP_READ);
            }

            //查看是read事件
            if (key.isReadable()){
                //开辟缓存空间
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                SocketChannel socketChannel = (SocketChannel)key.channel();
                //读取数据
                int readBytes = socketChannel.read(readBuffer);
                //大于0,读取到了数据
                if (readBytes > 0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String msg = new String(bytes, "UTF-8");
                    System.out.println("receive msg:"+msg);
                    doWrite(socketChannel,System.currentTimeMillis()+"");
                }else if (readBytes < 0){
                    //等于-1 ,链路已经关闭,需要释放资源
                    key.cancel();
                    socketChannel.close();
                }else {
                    //等于0,没有可读取数据,忽略
                }

            }
        }

    }

    private void doWrite(SocketChannel socketChannel, String response) throws IOException {

        byte[] bytes = response.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);

    }

	public static void main(String[] args) throws IOException {
        MultiplexerTimeServer server = new MultiplexerTimeServer(8088);
        new Thread(server,"timerServer-001").start();
    }
}

客户端代码

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

public class TimeClinetHandler implements Runnable {

    private String host;
    private int port ;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop = false;

    public TimeClinetHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try{
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        }catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        try{
            doConnection();
        }catch (Exception e){
            e.printStackTrace();
            System.exit(-1);
        }
        System.out.println("after connect");
        while (!stop){
            try{
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                SelectionKey key;
                while (iterator.hasNext()){
                    key = iterator.next();
                    iterator.remove();
                    try{
                        handInput(key);
                    }catch (Exception e){
                        key.cancel();
                        if (key.channel() != null)
                            key.channel().close();
                    }
                }

            }catch (Exception e){
                e.printStackTrace();
                System.exit(-1);
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handInput(SelectionKey key) throws IOException {
        if (key.isValid()){
            SocketChannel channel = (SocketChannel)key.channel();
            //判断是否连接成功
            if (key.isConnectable()){
                //完成了连接
                if (channel.finishConnect()){
                    channel.register(selector,SelectionKey.OP_READ);
                    doWrite(socketChannel);
                }else {
                    System.exit(-1);
                }
            }

            //判断是否可读状态
            if (key.isReadable()){
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readbytes = channel.read(readBuffer);
                if (readbytes > 0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String msg = new String(bytes, "UTF-8");
                    System.out.println(" client get msg:"+msg);
                    this.stop = true ;
                }else if (readbytes < 0){
                    key.cancel();
                    channel.close();
                }
            }
        }
    }

    private void stop() {
        this.stop = true;
    }

    private void doConnection() throws IOException {
        //如果连接成功,则注册到多路复用器上,监听读事件
        if (socketChannel.connect(new InetSocketAddress(host,port))) {
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else {
            //注册到多路复用器上,监听连接事件
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite(SocketChannel socketChannel) throws IOException {
        byte[] bytes = "query for time".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        if (!writeBuffer.hasRemaining()){
            System.out.println("client send msg succ");
        }
    }
	
	public static void main(String[] args) throws IOException {
        new Thread(new TimeClinetHandler("127.0.0.1",8088)).start();
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值