使用 NIO 实现 echo 服务器

NIO相关知识点

IO、NIO、AIO 内部原理分析
NIO 之 Selector实现原理
NIO 之 Channel实现原理
NIO 之 ByteBuffer实现原理

服务器使用NIO来实现一个echo协议的服务器。
echo协议简单也很有用,可以测试网络连接。

消息的格式为:消息长度(int)+消息内容

通过消息长度来进行socket分包,防止读取出现半包、粘包等问题。

服务端

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;
import java.util.Set;

public class NioEchoServer {

    public static void server() {
        ServerSocketChannel ssc = null;
        Selector selector = null;
        try {
            ssc = ServerSocketChannel.open();
            //设置为非阻塞
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(9000), 10);
            selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }

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

            try {
                Set<SelectionKey> set = selector.selectedKeys();
                Iterator<SelectionKey> it = set.iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    set.remove(key);
                    try {
                        if (key.isAcceptable()) {
                            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                            SocketChannel clientChannel = serverChannel.accept();
                            clientChannel.configureBlocking(false);
                            MessageInfo messageInfo = new MessageInfo();
                            clientChannel.register(selector, SelectionKey.OP_READ, messageInfo);
                        } else if (key.isReadable()) {
                            SocketChannel clientChannel = (SocketChannel) key.channel();
                            MessageInfo messageInfo = (MessageInfo)key.attachment();

                            if(messageInfo.getLenBuf() == null){
                                messageInfo.setLenBuf(ByteBuffer.allocate(4));
                            }

                            //消息长度
                            int len = messageInfo.getLen();
                            //判断消息长度是否读取完成
                            if(len!=-1){
                                if(messageInfo.contentBuf == null){
                                    //创建指定消息长度的buf
                                    messageInfo.contentBuf = ByteBuffer.allocate(len);
                                }
                                //如果消息未读取完成,继续读取
                                if(messageInfo.contentBuf.position()<len){
                                    if(clientChannel.read(messageInfo.contentBuf)==-1){
                                        clientChannel.register(selector, SelectionKey.OP_WRITE, messageInfo);
                                    }
                                }

                                if(len==0){
                                    System.out.println("空消息");
                                    key.cancel();
                                    key.channel().close();
                                }else if(messageInfo.contentBuf.position()==len){
                                    messageInfo.contentBuf.flip();
                                    System.out.println(new String(messageInfo.contentBuf.array()));
//                                  clientChannel.register(selector, SelectionKey.OP_WRITE, messageInfo);
                                    key.interestOps(SelectionKey.OP_WRITE);
                                }
                            }
                            //消息长度未读取完成
                            else{
                                int i = clientChannel.read(messageInfo.getLenBuf());
                                if(i==-1){
                                    System.out.println("消息异常:"+messageInfo.getLenBuf());
                                    break;
                                }
                                if(messageInfo.getLenBuf().position()==4){
                                    messageInfo.getLenBuf().flip();
                                    messageInfo.setLen(messageInfo.getLenBuf().getInt());
                                }
                            }

                        }else if(key.isWritable()){
                            SocketChannel clientChannel = (SocketChannel) key.channel();
                            MessageInfo messageInfo = (MessageInfo)key.attachment();
                            messageInfo.lenBuf.rewind();
                            messageInfo.contentBuf.rewind();
                            ByteBuffer[] bufs = new ByteBuffer[]{messageInfo.lenBuf, messageInfo.contentBuf};
                            System.out.println(messageInfo.contentBuf.limit()+":"+messageInfo.contentBuf.capacity());
                            clientChannel.write(bufs);
                            key.cancel();
                            key.channel().close();
                        }
                    } catch (Exception e) {
                        key.cancel();
                        key.channel().close();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }

        }

        System.out.println("");

    }

    public static void main(String[] args) {
        server();
    }

    //消息对象
    static class MessageInfo {
        private int len=-1;
        private ByteBuffer lenBuf;
        private ByteBuffer contentBuf;

        public int getLen() {
            return len;
        }

        public void setLen(int len) {
            this.len = len;
        }

        public ByteBuffer getLenBuf() {
            return lenBuf;
        }

        public void setLenBuf(ByteBuffer lenBuf) {
            this.lenBuf = lenBuf;
        }

        public ByteBuffer getContentBuf() {
            return contentBuf;
        }

        public void setContentBuf(ByteBuffer contentBuf) {
            this.contentBuf = contentBuf;
        }
    }

}

客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NioEchoClient {

    public static void main(String[] args) {

        SocketAddress sa = new InetSocketAddress("127.0.0.1", 9000);
        try {
            SocketChannel client = SocketChannel.open(sa);

            byte[] data = "大家好".getBytes();
            ByteBuffer lenBuf = ByteBuffer.wrap(int2byte(data.length));
            ByteBuffer textBuf = ByteBuffer.wrap(data);
            ByteBuffer[] bufArray = new ByteBuffer[]{lenBuf, textBuf};
            client.write(bufArray);

            lenBuf.clear();
            textBuf.clear();
            client.read(bufArray);

            System.out.println("echo:"+new String(textBuf.array()));
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * int 转 byte[] 数组
     * @param len
     * @return
     */
    public static byte[] int2byte(int len) {
        byte[] b = new byte[4];
        b[0] = (byte) (len >> 24);
        b[1] = (byte) (len >> 16 & 0XFF);
        b[2] = (byte) (len >> 8 & 0XFF);
        b[3] = (byte) (len & 0XFF);
        return b;
    }
}

本人简书blog地址:http://www.jianshu.com/u/1f0067e24ff8    
点击这里快速进入简书

GIT地址:http://git.oschina.net/brucekankan/
点击这里快速进入GIT

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用NIO技术改写Echo项目的客户机/服务器设计的Java代码示例服务器端代码: ```java 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; public class NioEchoServer { private static final int BUF_SIZE = 1024; private static final int PORT = 8080; private static final int TIMEOUT = 3000; public static void main(String[] args) { selector(); } public static void selector() { Selector selector = null; ServerSocketChannel ssc = null; try { // 创建选择器 selector = Selector.open(); // 打开监听通道 ssc = ServerSocketChannel.open(); // 绑定端口 ssc.socket().bind(new InetSocketAddress(PORT)); // 设置为非阻塞模式 ssc.configureBlocking(false); // 注册选择器并监听接受事件 ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started and listen on port " + PORT + "..."); while (true) { // 等待事件 if (selector.select(TIMEOUT) == 0) { System.out.print("."); continue; } // 获取事件集合 Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); // 处理事件 handleKey(key); iter.remove(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (selector != null) { selector.close(); } if (ssc != null) { ssc.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static void handleKey(SelectionKey key) throws IOException { if (key.isAcceptable()) { // 处理接受事件 ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); sc.register(key.selector(), SelectionKey.OP_READ); } if (key.isReadable()) { // 处理读事件 SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); int len = sc.read(buf); if (len > 0) { buf.flip(); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); String msg = new String(bytes, "UTF-8"); System.out.println("Server received: " + msg); sc.register(key.selector(), SelectionKey.OP_WRITE); // 将读取到的数据写回客户端 ByteBuffer writeBuf = ByteBuffer.wrap(bytes); sc.write(writeBuf); } else if (len == -1) { System.out.println("Client closed..."); sc.close(); } } if (key.isWritable()) { // 处理写事件 SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); sc.write(buf); if (!buf.hasRemaining()) { key.interestOps(SelectionKey.OP_READ); } buf.compact(); } } } ``` 客户端代码: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; public class NioEchoClient { private static final int BUF_SIZE = 1024; private static final int PORT = 8080; public static void main(String[] args) { try { // 打开通道 SocketChannel sc = SocketChannel.open(); // 设置为非阻塞模式 sc.configureBlocking(false); // 连接服务器 sc.connect(new InetSocketAddress(PORT)); while (!sc.finishConnect()) { System.out.print("."); } System.out.println("Client connected..."); // 发送数据 ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); buf.put("Hello, NIO!".getBytes()); buf.flip(); sc.write(buf); // 接收数据 buf.clear(); int len = sc.read(buf); if (len > 0) { buf.flip(); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); String msg = new String(bytes, "UTF-8"); System.out.println("Client received: " + msg); } // 关闭通道 sc.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码示例中,服务器使用Selector监听ACCEPT、READ和WRITE事件,客户端使用SocketChannel与服务器建立连接,并发送和接收数据。通过NIO技术,可以实现多个客户端连接共享少量线程的并发处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值