zoukankan      html  css  js  c++  java
  • 一个简单的NIO服务示例

    package nio;

    import java.io.IOException;
    import java.net.InetAddress;
    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;

    /**
    * 一个简单的NIO 服务的例子
    * @author Kaka
    *
    */
    public class NIOServer {
    //ServerSocketChannel 服务channel
    ServerSocketChannel ssc=null;
    //分发器
    Selector selector=null;
    //选择键
    SelectionKey sk=null;
    /**
    * 构造函数
    * @throws IOException
    */
    NIOServer() throws IOException{
    ssc=ServerSocketChannel.open();
    ssc.configureBlocking(false);
    InetAddress ia=InetAddress.getLocalHost();
    InetSocketAddress isa=new InetSocketAddress(ia,9000);
    ssc.socket().bind(isa);
    selector=Selector.open();
    sk=ssc.register(selector, SelectionKey.OP_ACCEPT);
    }
    /**
    * 服务器运行
    * @throws IOException
    */
    void run() throws IOException{
    while (true) {
    //取得事件数目
    int n=selector.select();
    if(n==0)
    continue;
    Iterator<SelectionKey> it=selector.selectedKeys().iterator();
    while(it.hasNext())
    {
    System.out.println("have...");
    SelectionKey key = (SelectionKey)it.next();
    it.remove(); 
    //轮训连接
    if(key.isAcceptable()){ 

    System.out.println("Acceptable");
    ServerSocketChannel server = 
    (ServerSocketChannel) key.channel(); 
    SocketChannel channel = server.accept();//获取SocketChannel来通信 
    ;
    channel.configureBlocking(false);
    //这个地方可以对channel进行处理,这里只是简单的往客户端写一个字符串
    channel.register(selector, SelectionKey.OP_READ);
    channel.write(ByteBuffer.wrap("hello".getBytes()));
    channel.close();
    }  //其它的轮训
    else if (key.isReadable()) { // 读信息

    System.out.println("readable");
    }
    }
    }
    }
    public static void main(String[] args) throws IOException {
    NIOServer server =new NIOServer();
    server.run();
    }

    }
    这时候可以使用telnet ip地址 9000来访问这个服务了
    正常情况应该能看到hello,然后是连接丢失的信息
  • 相关阅读:
    Python Django :HTTP生命周期
    Docker简介及Centos 7 安装[初步配置]
    python:Django 简介。
    python :Django url /views /Template 文件介绍
    python:异常处理及程序调试
    python之正则表达式【re】
    Day 21 python :面向对象 类的相关内置函数 /单例模式 /描述符
    Day 22: 软件开发目录设计规范
    Day 20: 面向对象【多态,封装,反射】字符串模块导入/内置attr /包装 /授权
    SpringCloud教程 | 第九篇: 服务链路追踪(Spring Cloud Sleuth)
  • 原文地址:https://www.cnblogs.com/macula7/p/1960400.html
Copyright © 2011-2022 走看看