Java 基于NIO的client与server

同步阻塞IO(BIO)

同步非阻塞IO(NIO) jdk1.7之前

异步阻塞IO(AIO) jdk1.7 及以后

 

ackage com.willow.io;

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

/*
 * 一、使用 NIO 完成网络通信的三个核心:
 *
 * 1. 通道(Channel):负责连接
 *
 * 	   java.nio.channels.Channel 接口:
 * 			|--SelectableChannel
 * 				|--SocketChannel
 * 				|--ServerSocketChannel
 * 				|--DatagramChannel
 *
 * 				|--Pipe.SinkChannel
 * 				|--Pipe.SourceChannel
 *
 * 2. 缓冲区(Buffer):负责数据的存取
 *
 * 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况
 *
 */

//NIO 客户端
public class NioClient {

    public static void main(String arg[]) {
        System.out.println("客户端已经启动.............");
        try {
            //1、创建socker通道
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
            //2、切换异步非阻塞
            socketChannel.configureBlocking(false); //1.7及以上
            //3、指定缓冲区大小
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            byteBuffer.put(new Date().toString().getBytes());
            //4、切换到读取模式
            byteBuffer.flip();
            //5、写入到缓冲区
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
            //6、关闭通道
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



//NIO 服务端
class NioServer {


    public static void main(String arg[]) {

        System.out.println("服务器端启动");
        try {
            //1、创建服务器端通道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //2、切换异步非阻塞
            serverSocketChannel.configureBlocking(false); //1.7及以上
            //3、切换读取模式
            serverSocketChannel.bind(new InetSocketAddress(8080));
            //4、获取选择器
            Selector selector = Selector.open();
            //5、将通道注册到选择器中去,并且监听已经收到的事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            //6、轮询获取“已经准备就绪的”的事件
            while (selector.select() > 0) {
                //7、获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    //8、获取准备“就绪”的是事件
                    SelectionKey sk = iterator.next();
                    //9、 判断具体是什么事件准备就绪
                    if (sk.isAcceptable()) {
                        //10、 若“接收就绪”,获取客户端连接
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //11、 切换非阻塞模式
                        socketChannel.configureBlocking(false);
                        //12、 将该通道注册到选择器上
                        socketChannel.register(selector, SelectionKey.OP_READ);


                    } else if (sk.isReadable()){
                        //13、 获取当前选择器上“读就绪”状态的通道
                        SocketChannel sChannel = (SocketChannel) sk.channel();

                        //14、 指定缓冲区大小,读取数据
                        ByteBuffer buf = ByteBuffer.allocate(1024);

                        int len = 0;
                        while ((len = sChannel.read(buf)) > 0) {  //sChannel 读取数据到ByteBuffer
                            buf.flip(); //切换到读取模式
                            String str = new String(buf.array(), 0, len);  //读取
                            System.out.println("str:"+str);
                            buf.clear();
                        }

                    }

                    //15. 取消选择键 SelectionKey
                    iterator.remove();

                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现一个和Netty一样的功能Server端和client端,可以使用Java NIO来进行实现。下面是一个简单的示例代码: ### Server端 ```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; import java.util.Set; public class NioServer { private Selector selector; private ByteBuffer readBuffer = ByteBuffer.allocate(1024); private ByteBuffer writeBuffer = ByteBuffer.allocate(1024); public NioServer(int port) { try { // 创建ServerSocketChannel对象并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); // 创建Selector对象 selector = Selector.open(); // 将ServerSocketChannel注册到Selector上,并设置为监听OP_ACCEPT事件 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server started, listening on port " + port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void start() { try { while (true) { // 阻塞等待事件的发生 selector.select(); // 获取发生事件的SelectionKey集合 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); if (selectionKey.isAcceptable()) { // ServerSocketChannel可以接收客户端连接 ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_READ); System.out.println("Client " + socketChannel.getRemoteAddress() + " connected."); } else if (selectionKey.isReadable()) { // SocketChannel可以读取数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); readBuffer.clear(); int numRead = socketChannel.read(readBuffer); if (numRead == -1) { // 客户端关闭连接 selectionKey.cancel(); socketChannel.close(); System.out.println("Client " + socketChannel.getRemoteAddress() + " disconnected."); } else { // 处理读取到的数据 String request = new String(readBuffer.array(), 0, numRead); System.out.println("Received request from client " + socketChannel.getRemoteAddress() + ": " + request); socketChannel.register(selector, SelectionKey.OP_WRITE); } } else if (selectionKey.isWritable()) { // SocketChannel可以写入数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); writeBuffer.clear(); String response = "Hello from server!"; writeBuffer.put(response.getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); socketChannel.register(selector, SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { NioServer server = new NioServer(8888); server.start(); } } ``` ### Client端 ```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.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioClient { private Selector selector; private ByteBuffer readBuffer = ByteBuffer.allocate(1024); private ByteBuffer writeBuffer = ByteBuffer.allocate(1024); public NioClient(String host, int port) { try { // 创建SocketChannel对象并连接服务器 SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress(host, port)); // 创建Selector对象 selector = Selector.open(); // 将SocketChannel注册到Selector上,并设置为监听OP_CONNECT事件 socketChannel.register(selector, SelectionKey.OP_CONNECT); System.out.println("Connecting to server " + host + ":" + port); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public void start() { try { while (true) { // 阻塞等待事件的发生 selector.select(); // 获取发生事件的SelectionKey集合 Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey selectionKey = iterator.next(); iterator.remove(); if (selectionKey.isConnectable()) { // SocketChannel已连接到服务器 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } socketChannel.configureBlocking(false); socketChannel.register(selector, SelectionKey.OP_WRITE); System.out.println("Connected to server " + socketChannel.getRemoteAddress()); } else if (selectionKey.isReadable()) { // SocketChannel可以读取数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); readBuffer.clear(); int numRead = socketChannel.read(readBuffer); if (numRead == -1) { // 服务器关闭连接 selectionKey.cancel(); socketChannel.close(); System.out.println("Server " + socketChannel.getRemoteAddress() + " disconnected."); } else { // 处理读取到的数据 String response = new String(readBuffer.array(), 0, numRead); System.out.println("Received response from server " + socketChannel.getRemoteAddress() + ": " + response); socketChannel.register(selector, SelectionKey.OP_WRITE); } } else if (selectionKey.isWritable()) { // SocketChannel可以写入数据 SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); writeBuffer.clear(); String request = "Hello from client!"; writeBuffer.put(request.getBytes()); writeBuffer.flip(); socketChannel.write(writeBuffer); socketChannel.register(selector, SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { NioClient client = new NioClient("localhost", 8888); client.start(); } } ``` 这个示例代码实现了一个简单的NIO ServerClient,可以接收客户端连接,读取客户端发送的数据,并回复一条消息。虽然它没有Netty那么强大,但是可以作为一个参考来了解Java NIO的基本原理和使用方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值