Java NIO通过Selector实现客户端与服务端交互

85 篇文章 1 订阅

服务端

public class Server {
    //源码注释:requested maximum length of the queue of incoming connections.
    //BACK_LOG影响的accept队列大小
    public static final int BACK_LOG = 1024;

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        //设置非阻塞
        serverChannel.configureBlocking(false);
        //绑定端口,在服务端监听
        serverChannel.bind(new InetSocketAddress("127.0.0.1", 8888), BACK_LOG);
        //serverChannel.socket().bind(new InetSocketAddress("127.0.0.1",8888), BACK_LOG);
        //创建Selector对象
        Selector selector = Selector.open();
        //ServerSocketChannel注册到Selector
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        for (; ; ) {
            if (selector.select(1000) == 0) {
                System.out.println("服务器等待了1秒,无连接");
                continue;
            }
            //关注事件集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //如果是OP_ACCEPT,有新的客户端连接
                if (key.isAcceptable()) {
                    SocketChannel channel = serverChannel.accept();
                    System.out.println("连接成功,SocketChannel:" + channel.hashCode());
                    channel.configureBlocking(false);
                    //关联buffer
                    channel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    //把通道数据放入缓冲区
                    channel.read(buffer);
                }
                //移除Selection,因为多线程,要防止重复操作
                iterator.remove();
            }
        }
    }
}

客户端

public class Client {
    public static void main(String[] args) throws IOException {
        //打开一个网络通道
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        //连接服务器
        if (!channel.connect(new InetSocketAddress("127.0.0.1", 8888))) {
            while (!channel.finishConnect()) {
                System.out.println("连接需要时间,不阻塞,边做其他工作");
            }
        }
        String str = "你好,chen";
        //NIO wrap 会自动根据你字节数创建相应大小的buffer
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //把缓冲区数据放入通道
        channel.write(buffer);
        System.in.read();
    }
}

结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 NIO(Non-blocking I/O)实现 Java客户端服务端可以提高网络通信的效率。下面是一个简单的示例,演示了如何使用 NIO 实现一个简单的客户端服务端。 首先是服务端代码: ```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 static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) { selector(); } public static void handleAccept(SelectionKey key) throws IOException { ServerSocketChannel ssChannel = (ServerSocketChannel) key.channel(); SocketChannel sc = ssChannel.accept(); sc.configureBlocking(false); sc.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocateDirect(BUF_SIZE)); } public static void handleRead(SelectionKey key) throws IOException { SocketChannel sc = (SocketChannel) key.channel(); ByteBuffer buf = (ByteBuffer) key.attachment(); int bytesRead = sc.read(buf); while (bytesRead > 0) { buf.flip(); while (buf.hasRemaining()) { System.out.print((char) buf.get()); } System.out.println(); buf.clear(); bytesRead = sc.read(buf); } if (bytesRead == -1) { sc.close(); } } public static void handleWrite(SelectionKey key) throws IOException { ByteBuffer buf = (ByteBuffer) key.attachment(); buf.flip(); SocketChannel sc = (SocketChannel) key.channel(); while (buf.hasRemaining()) { sc.write(buf); } buf.compact(); } 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); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isAcceptable()) { handleAccept(key); } if (key.isReadable()) { handleRead(key); } if (key.isWritable() && key.isValid()) { handleWrite(key); } if (key.isConnectable()) { System.out.println("isConnectable = true"); } iterator.remove(); } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (selector != null) { selector.close(); } if (ssc != null) { ssc.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 然后是客户端代码: ```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.Scanner; import java.util.Set; public class NioClient { private static int BUF_SIZE = 1024; private static int PORT = 8080; private static int TIMEOUT = 3000; public static void main(String[] args) throws IOException { SocketChannel clientChannel = SocketChannel.open(); clientChannel.configureBlocking(false); Selector selector = Selector.open(); clientChannel.register(selector, SelectionKey.OP_CONNECT); clientChannel.connect(new InetSocketAddress(PORT)); while (true) { if (selector.select(TIMEOUT) == 0) { System.out.println("=="); continue; } Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); if (key.isConnectable()) { SocketChannel channel = (SocketChannel) key.channel(); if (channel.isConnectionPending()) { channel.finishConnect(); } channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); Scanner scanner = new Scanner(System.in); String message = scanner.nextLine(); channel.write(ByteBuffer.wrap(message.getBytes())); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); ByteBuffer buffer = ByteBuffer.allocate(BUF_SIZE); int bytesRead = channel.read(buffer); while (bytesRead > 0) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } System.out.println(); buffer.clear(); bytesRead = channel.read(buffer); } } iterator.remove(); } } } } ``` 这里的服务端监听端口为 8080,客户端连接的端口也为 8080。客户端首先向服务端发送一条消息,然后等待服务端的响应。当服务端接收到客户端的消息后,就会输出到控制台,并将消息原封不动地返回给客户端客户端接收到服务端的响应后,也会将其输出到控制台。 注意,这个示例只是一个简单的演示,实际开发中需要考虑更多的因素,例如线程安全、异常处理等等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值