基于Java NIO 的socket通信实例

服务端代码

package com.lp.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;

public class NioServerSocket {

    public static void main(String[] args) {

        HandlerSelectionKey handler = new HandlerHandlerSelectionKeyImpl();

        try {
            //创建 ServerSocketChannel
            ServerSocketChannel server = ServerSocketChannel.open();
            server.configureBlocking(false);
            server.bind(new InetSocketAddress("localhost", 12345));
            //创建 Selector
            Selector selector = Selector.open();
            server.register(selector, SelectionKey.OP_ACCEPT);
            //死循环,持续接收 客户端连接
            while(true) {
                //selector.select(); 是阻塞方法
                int keys = selector.select();
                if(keys > 0) {
                    Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                    while(it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        //处理 SelectionKey
                        handler.handler(key, selector);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * SelectionKey 处理接口
     *
     */
    public static interface HandlerSelectionKey {

        public void handler(SelectionKey key, Selector selector) throws IOException;

    }

    /**
     * SelectionKey 接口 实现类
     *
     */
    public static class HandlerHandlerSelectionKeyImpl implements HandlerSelectionKey {

        @Override
        public void handler(SelectionKey key, Selector selector) throws IOException {
            int keyState = selectionKeyState(key);
            switch (keyState) {
            case SelectionKey.OP_ACCEPT:
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                accept(serverSocketChannel, selector);
                break;
            case SelectionKey.OP_READ:
                SocketChannel readSocketChannel = (SocketChannel) key.channel();
                read(readSocketChannel, selector);
                break;

            case SelectionKey.OP_WRITE:
                SocketChannel writeSocketChannel = (SocketChannel) key.channel();
                write(writeSocketChannel, selector);
                break;
            }
        }
        /**
         * 获取 SelectionKey 是什么事件
         * @param key
         * @return
         */
        private int selectionKeyState(SelectionKey key) {
            if(key.isAcceptable()) {
                return SelectionKey.OP_ACCEPT;
            } else if(key.isReadable()) {
                return SelectionKey.OP_READ;
            } else if(key.isWritable()) {
                return SelectionKey.OP_WRITE;
            }
            return -1;
        }

        /**
         * 接口客户端请求
         * @param serverSocketChannel
         * @param selector
         * @throws IOException
         */
        private void accept(ServerSocketChannel serverSocketChannel, Selector selector) throws IOException {
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            //将 channel 注册到  Selector
            socketChannel.register(selector, SelectionKey.OP_READ);
        }

        /**
         * 读取客户端发送过来的信息
         * @param socketChannel
         * @param selector
         * @throws IOException
         */
        private void read(SocketChannel socketChannel, Selector selector) throws IOException {
            ByteBuffer readBuffer = ByteBuffer.allocate(8192);
            int readBytes = socketChannel.read(readBuffer);
            if(readBytes > 0) {
                System.out.println("客户端发送来的消息");
                System.out.println(new String(readBuffer.array(), 0, readBytes));
            }
            //将 channel 注册到  Selector
            socketChannel.register(selector, SelectionKey.OP_WRITE);
        }

        /**
         * 响应客户端请求
         * @param socketChannel
         * @param selector
         * @throws IOException
         */
        private void write(SocketChannel socketChannel, Selector selector) throws IOException {
            //响应消息
            String responseMsg = "hello client, i am server";
            byte[] responseByte = responseMsg.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(responseByte.length);
            writeBuffer.put(responseByte);
            writeBuffer.flip();
            //响应客户端
            socketChannel.write(writeBuffer);
            socketChannel.finishConnect();
            socketChannel.close();
        }

    }


}

客户端代码

package com.lp.socket;

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

public class NioClientSocket {

    public static void main(String[] args) throws IOException {
        //打开 SocketChannel
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 12345));
        //设置为 非阻塞
        socketChannel.configureBlocking(false);
        //给服务端发送信息
        socketChannel.write(ByteBuffer.wrap("Actions speak louder than words!".getBytes()));

        ByteBuffer readBuffer = ByteBuffer.allocate(512);
        while (true) {
            readBuffer.clear();
            int readBytes = socketChannel.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                System.out.println("Client: readBytes = " + readBytes);
                System.out.println("Client: data = " + new String(readBuffer.array(), 0, readBytes));
                socketChannel.close();
                break;
            }
        }

    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值