频道栏目
首页 > 程序开发 > 软件开发 > Java > 正文
netty使用:java NIO
2017-06-19 09:39:09      个评论    来源:  
收藏   我要投稿

netty使用:java NIO

使用java nio api实现一个简单的EchoServer

一.server代码

package nio_demo;

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

/**
 * @Type NioEchoServer.java
 * @Desc 
 * @author wj
 * @date 2017年6月12日 上午11:25:06
 * @version 
 */
public class NioEchoServer {

    public static void serve(int port) throws IOException {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        ServerSocket ss = serverChannel.socket();

        InetSocketAddress address = new InetSocketAddress(port);

        ss.bind(address);
        serverChannel.configureBlocking(false);

        Selector selector = Selector.open();

        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            try {
                selector.select();
            } catch (IOException ex) {
                ex.printStackTrace();
                break;
            }

            Set readyKeys = selector.selectedKeys();

            Iterator iter = readyKeys.iterator();

            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();

                try {
                    if (key.isAcceptable()) {

                        ServerSocketChannel server = (ServerSocketChannel) key.channel();

                        SocketChannel client = server.accept();

                        System.out.println("accepted connection from " + client);

                        client.configureBlocking(false);
                        client.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE,
                                ByteBuffer.allocate(100));

                    }

                    if (key.isReadable()) {
                        SocketChannel client = (SocketChannel) key.channel();

                        ByteBuffer output = (ByteBuffer) key.attachment();

                        client.read(output);

                        System.out.println("read data len:" + output.position());
                    }

                    if (key.isWritable()) {
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer output = (ByteBuffer) key.attachment();

                        if(output.position() > 0){
                            output.flip();
                            int number = 0;
                            number = client.write(output);
                            System.out.println("write number:" + number);
                            output.compact();
                        }           
                    }
                } catch (IOException ex) {
                    System.out.println("connection  exception !!!");
                    key.cancel();
                    try {
                        key.channel().close();
                    } catch (IOException e) {

                    }
                }
            }
        }
    }

    public static void main(String args[]) {

        try {
            serve(1234);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

二.测试
测试代码:

package test_nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @Type TestNio.java
 * @Desc 
 * @author wangjie
 * @date 2017年6月12日 下午3:10:14
 * @version 
 */
public class TestNio {
    static public void main(String args[]){
        try{
            InetSocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
            SocketChannel clientChannel = SocketChannel.open();
            if(true == clientChannel.connect(address)){
                System.out.println("connect success!");
            }

            for(int i = 0;i < 5; ++i){
                String str = "test " + i + "!";
                ByteBuffer ibuff = ByteBuffer.allocate(100);
                ByteBuffer obuff = ByteBuffer.allocate(100);
                ibuff.put(str.getBytes("utf-8"));
                ibuff.flip();
                clientChannel.write(ibuff);

                clientChannel.read(obuff);
                obuff.flip();
                byte output[] = new byte[100];
                int opos = obuff.remaining();
                obuff.get(output, 0, obuff.remaining());
                System.out.println("");
                String ostr = new String(output, "utf-8");

                System.out.println("recv, lenth:"+ opos + " :" + ostr);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}

测试结果:

connect success!
recv, lenth:7 :test 0!
recv, lenth:7 :test 1!
recv, lenth:7 :test 2!
recv, lenth:7 :test 3!
recv, lenth:7 :test 4!
点击复制链接 与好友分享!回本站首页
上一篇:Java-Arrays.asList()使用中的问题
下一篇:CCF数字排序
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 |

版权所有: 88bifa.com--致力于做实用的IT技术学习网站