nio 测试小代码

本文介绍了一个使用Java NIO实现的服务端应用案例。通过ServerSocketChannel和Selector处理客户端连接请求,并根据不同操作类型(如读、写等)注册相应的SelectionKey。文章详细展示了如何接收客户端消息并作出响应。

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

package com.io;


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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * \* Description:这里是不允许 这个操作的。因为SocketChannel 不允许有这个状态
 * \* Created with IntelliJ IDEA.
 * \* User: fdes
 * \* Date: 2018/9/5
 * \* Time: 13:44
 * \
 */
public class ServerNio {

    private ServerSocketChannel ssc = null;
    private Selector selector = null;

    public static void main(String[] args) throws IOException {
        ServerNio ss = new ServerNio();
        ss.initServerChannel(8888);
        ss.linsternServerChannel();
    }

    private void initServerChannel(int port) throws IOException {
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port));

        selector = Selector.open();
        ssc.register(selector,SelectionKey.OP_ACCEPT);
    }

    private void linsternServerChannel() throws IOException {
        while (true){
            this.selector.select();
            Iterator<SelectionKey>  iterator = this.selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                hanlder(key);
            }
        }

    }

    private void hanlder(SelectionKey key) throws IOException {

        if (key.isAcceptable()){
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel)key.channel();
            SocketChannel sc = serverSocketChannel.accept();
            sc.configureBlocking(false);
            sc.register(this.selector,SelectionKey.OP_READ);
        } else if (key.isReadable()){
            SocketChannel sc = (SocketChannel)key.channel();
            ByteBuffer byteBuffers = ByteBuffer.allocate(1024);
            int read = sc.read(byteBuffers);
            if (read > 0){
                String command = new String(byteBuffers.array(),0,read,"utf-8");
                if (command.equals("re")){
                    System.out.println("=============re============"+command);
                    sc.register(this.selector,SelectionKey.OP_CONNECT);
                } else if (command.equals("wirte")){
                    System.out.println("==========wirte==============="+command);
                    sc.register(this.selector,SelectionKey.OP_WRITE);
                } else if (command.equals("error")){
                    System.out.println("==========error==============="+command);
                    //
                    sc.register(this.selector,SelectionKey.OP_ACCEPT);
                } else{
                    System.out.println("========================="+command);
                }
            } else {
                System.out.println("客户端没有数据......");
            }
        } else if (key.isWritable()){
            System.out.println("客户端进行写操作......");
            SocketChannel sc = (SocketChannel)key.channel();
            ByteBuffer byteBuffers = ByteBuffer.allocate(1024);
            byte[] bytes = "你好,客户端1111111".getBytes();
            sc.write(byteBuffers.get(bytes));
            sc.register(this.selector,SelectionKey.OP_READ);
        }

    }

}

代码做个笔记,方便以后复习:

1:SocketChannel (客户端) 是不允许有 SelectionKey.OP_ACCEPT(接受就绪)状态。

2:ServerSocketChannel  底层调用的还是ServerSocket   (ssc.socket() 返回的就是)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值