intellij idea安装 mysql视频 io background UIkit Backbonejs vue安装 vue开发 安卓小程序源码 matlab中log函数 oracle删除字段 java数据分析 hbase端口 ab软启动器 solr索引 mac上传文件到linux matlab跳出for循环 matlab中不等于怎么表示 docker启动命令 mysql临时表 python入门指南 java基础 java如何连接mysql java索引 java字符串函数 jb51 海鸥浏览器 ezcad2 js轮播图代码 超级力量2修改 为什么英雄联盟无法连接服务器 小洛快跑 脚本网站 sendto函数 cad乘号 微信昵称特殊字符保存 数据库编程软件 类似迅雷的下载软件 文字转音频软件 ssh框架原理及流程
当前位置: 首页 > 学习教程  > 编程语言

java使用Selector进行socket

2020/12/5 10:20:44 文章标签:

服务端 /*** Auther: wxy* Date: 2020/11/29 20:49* Description:*/ public class WebServer {public static void main(String[] args) {try {//创建ServerSocket通道ServerSocketChannel ssc ServerSocketChannel.open();//ServerSocket监听8000端口ssc.socket().bind(new …

服务端

/**
 * @Auther: wxy
 * @Date: 2020/11/29 20:49
 * @Description:
 */
public class WebServer {

    public static void main(String[] args) {
        try {
            //创建ServerSocket通道
            ServerSocketChannel ssc = ServerSocketChannel.open();
            //ServerSocket监听8000端口
            ssc.socket().bind(new InetSocketAddress("127.0.0.1", 8000));
            //设置通道为非阻塞  必须的
            ssc.configureBlocking(false);

            //创建一个选择器
            Selector selector = Selector.open();
            // 注册 channel,并且指定感兴趣的事件是 Accept
            ssc.register(selector, SelectionKey.OP_ACCEPT);

            ByteBuffer readBuff = ByteBuffer.allocate(1024);
            ByteBuffer writeBuff = ByteBuffer.allocate(128);
            writeBuff.put("received".getBytes());
            writeBuff.flip();

            while (true) {

                //主线程阻塞在`selector`的`select`方法中
                //- 当选择器发现`socket`就绪了,某个socket就绪了。就会唤醒主线程,
                //- 然后咱们可以通过`selector` 获取就绪状态的`socket` 进行相应的处理。
                int nReady = selector.select();
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> it = keys.iterator();

                //需要遍历一次
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    it.remove();

                    if (key.isAcceptable()) {
                        // 创建新的连接,并且把连接注册到selector上,而且,
                        // 声明这个channel只对读操作感兴趣。
                        SocketChannel socketChannel = ssc.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }
                    //可读
                    else if (key.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        readBuff.clear();
                        socketChannel.read(readBuff);

                        readBuff.flip();
                        System.out.println("received : " + new String(readBuff.array()));
                        key.interestOps(SelectionKey.OP_WRITE);
                    }
                    //可写
                    else if (key.isWritable()) {
                        writeBuff.rewind();
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        socketChannel.write(writeBuff);
                        key.interestOps(SelectionKey.OP_READ);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端


/**
 * @Auther: wxy
 * @Date: 2020/11/29 20:48
 * @Description:
 */
public class WebClient {
    public static void main(String[] args) throws IOException {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 8000));

            ByteBuffer writeBuffer = ByteBuffer.allocate(32);
            ByteBuffer readBuffer = ByteBuffer.allocate(32);

            writeBuffer.put("hello".getBytes());
            writeBuffer.flip();

           // while (true) {
                writeBuffer.rewind();
                socketChannel.write(writeBuffer);
                readBuffer.clear();
                socketChannel.read(readBuffer);
          //  }
        } catch (IOException e) {
        }
    }
}

本文链接: http://www.dtmao.cc/news_show_450200.shtml

附件下载

相关教程

    暂无相关的数据...

共有条评论 网友评论

验证码: 看不清楚?