NIO实现客户端、服务端

NIO实现服务端

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;
/**
 * @author TAO
 * @description: NIOServer
 * @date 2021/6/27 23:37
 */
public class NIOServer {

    public static void main(String[] args) throws Exception {

        //1.创建ServerSocketChannel --> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        ///2.得到一个Selector对象
        Selector selector = Selector.open();

        //3.绑定一个端口6666在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));

        //4.设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //5.把ServerSocketChannel注册到selector 监听事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //6.循环等待客户端连接(干活)
        while (true) {

            //6.1 这里我们等待1秒,如果没有事件发生,返回(监控客户端)
            if (selector.select(1000)==0){//nio非阻塞式的优势
                System.out.println("服务端等待1秒,无连接");
                continue;
            }

            //如果返回的>0,
            // 1.返回的>0标识获取到关注的事件
            // 2.selector.selectedKeys() 返回关注的时间集合
            // 通过selectionKeySets 方向获取通道
            //6.2 得到SelectionKey,判断通道里的事件
            Iterator<SelectionKey> keyIterator=selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {

                //获取到SelectionKey
                SelectionKey key = keyIterator.next();

                //根据key 对应的通道发生的事件做对应的处理
                if (key.isAcceptable()) {//如果是 OP_ACCEPT ,有新的客户端连接 客户端连接请求事件
                    //该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();

                    //System.out.println("客户端连接成功!!!生成了一个socketChannel--->"+socketChannel.hashCode());

                    //将socketChannel设置为非阻塞的
                    socketChannel.configureBlocking(false);//防止此异常 Exception in thread "main" java.nio.channels.IllegalBlockingModeException

                    //将socketChannel 注册到selector 关注事件为OP_READ
                    //关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }

                if (key.isReadable()){//发生OP_READ 读取客户端数据事件
                    //通过key方向获取对应的channel
                    SocketChannel channel = (SocketChannel) key.channel();

                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();

                    channel.read(buffer);
                    System.out.println("form 客户端"+new String(buffer.array()));
                }
                //6.3 手动从集合中移除当前的selectionKey,防止重复操作
                keyIterator.remove();
            }
        }
    }
}

NIO实现客户端

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

/**
* @description: NIOClient
* @author TAO
* @date 2021/6/27 23:57
*/
public class NIOClient {

    public static void main(String[] args) throws IOException {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();

        //设置为非阻塞
        socketChannel.configureBlocking(false);

        //根据服务端的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)){

            while (!socketChannel.finishConnect()){
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他操作...");
            }
        }

        //如果连接成功,就发送数据
        String str = "hello";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,将buffer数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

程序员劝退师-TAO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值