NIO、ServerSocketChannel常用方法、NIO方式实现客户端与服务端通信demo

版权声明:转载请注明出处--mosterRan https://blog.csdn.net/qq_35975685/article/details/84929933

ServerSocket是-BIO的网络编程通信方式
ServerSocketChannel-NIO(new io)是新的IO网络编程通信方式,他和BIO最大不同在于NIO是异步的方式,而BIO是同步的方式

ServerSocketChannel:用于面向流的侦听套接字可选通道

类树形图
在这里插入图片描述

ServerSocketChannel常用方法:

  • SocketChannel accept():接受此频道套接字的链接
  • ServerSocketChannel bind(SocketAddress local, int backlog):将通道的套接字绑定到本地地址,并配置套接字以监听链接,backlog为套接字上挂起的连接的最大数量,如果backlog参数的值为0或负值,则使用实现特定的默认值(默认为0)
  • SocketAddress getLocalAddress():返回此通道套接字所丙丁的套接字地址
  • static ServerSocketChannel open():打开服务器通道
  • ServerSocketChannel setOption(SocketOption name, T value):设置套接字选项的值
  • ServerSocket socket():检索与此通道关联的服务器套接字
  • int validOps():返回此频道支持的操作的操作集,如SelectionKey.OP_ACCEPT

下面的方法是从 AbstractSelectableChannel
继承下来的常用的如下

  • Object blockingLock():检索 configureBlocking 和 register 方法同步的对象
  • SelecttableChannel configureBlocking(boolean block)调整此频道的阻塞模式(true:阻塞模式 false:非阻塞模式)
  • void implCloseChannel():关闭此频道 会调用下面的implCloseSelectableChannel,并且关闭密钥
  • void implCloseSelectableChannel():关闭此选择的频道
  • boolean isBlocking():告诉这个通道上的每个I/O操作是否阻塞直到完成,如果结果为tue,则当前通道处于阻塞模式
  • boolean isRegistered():告知这个频道当前是否在任何选择器上注册
  • SelectionKey keyFor(Selector sel):检索表示频道注册的键与给定的选择器
  • SelectorProvider provider():返回创建此通道的提供程序
  • SelectionKey register(Selector sel, int ops, Object att):使用给定的选择器注册此频道,返回一个选择键,sel要注册的选择器、ops为所得密钥设置、att为密钥的附件,可能为null

下面为实例demo
服务器端Main方法

package com.zhr.nio;

public class TimeServer {

    public static void main(String[] args) {
        int port = 8080;
        if(args != null && args.length > 0){
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
        new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();


    }
}

服务器处理过程

package com.zhr.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class MultiplexerTimeServer implements Runnable {

    private Selector selector;

    private ServerSocketChannel servChannel;

    private volatile boolean stop;

    /**
     * 初始化多路复用器,绑定监听端口
     */
    public MultiplexerTimeServer(int port) {

        try {
            selector = Selector.open();
            servChannel = ServerSocketChannel.open();
            servChannel.configureBlocking(false);
            servChannel.socket().bind(new InetSocketAddress(port), 1024);
            servChannel.register(selector,
                    SelectionKey.OP_ACCEPT);
            System.out.println("The time server is start in port :" + port);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(1);
        }

    }

    public void stop() {
        this.stop = true;
    }

    public void run() {
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();
                    try {
                        handleInput(key);
                    } catch (Exception e) {
                        if (key != null) {
                            key.cancel();
                            if (key.channel() != null) {
                                key.channel().close();
                            }
                        }
                        e.printStackTrace();
                    }
                }

            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    private void handleInput(SelectionKey key) throws IOException {
        //密钥是否有效
        if (key.isValid()) {
            //这个密钥通道是否准备好接受新的套接字连接
            if (key.isAcceptable()) {
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("The time server receive order :" + body);
                    String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(System.currentTimeMillis()).toString()
                            : "BAD ORDER";
                    doWrite(sc, currentTime);

                } else if (readBytes < 0) {
                    key.channel();
                    sc.close();
                } else {
                    ;//读到0字节,忽略
                }
            }
        }
    }

    private void doWrite(SocketChannel channel, String response) throws IOException {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer);
        }

    }
}

客户端Main方法

package com.zhr.nio;

public class TimeClient {
    public static void main(String[] args) {
        int port = 8080;
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        new Thread(new TimeClientHandle("127.0.0.1", port), "TimeClient-001")
                .start();
    }
}

客户端的处理器

package com.zhr.nio;

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 TimeClientHandle implements Runnable {

    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop;

    public TimeClientHandle(String host, int port) {
        this.host = host == null ? "127.0.0.1" : host;
        this.port = port;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void run() {

        try {
            doConnect();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    it.remove();

                    handleInput(key);

                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }

        }
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleInput(SelectionKey key) throws IOException {
        if (key.isValid()) {
            SocketChannel sc = (SocketChannel) key.channel();
            if (key.isConnectable()) {
                if (sc.finishConnect()) {
                    sc.register(selector, SelectionKey.OP_READ);
                    doWrite(sc);
                } else {
                    System.exit(1);//连接失败,程序退出
                }
            }
            if (key.isReadable()) {
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("Now is :" + body);
                    this.stop = true;
                } else if (readBytes < 0) {
                    key.cancel();
                    sc.close();
                } else {
                    ;//读到0字节,忽略
                }
            }
        }
    }

    private void doConnect() throws IOException {
        if (socketChannel.connect(new InetSocketAddress(host, port))) {
            socketChannel.register(selector, SelectionKey.OP_READ);
            doWrite(socketChannel);
        } else {
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
        }
    }

    private void doWrite(SocketChannel sc) throws IOException {
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
        if (!writeBuffer.hasRemaining()) {
            System.out.println("Send order 2 server succeed.");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35975685/article/details/84929933