• 九、Java NIO SocketChannel


    所有文章

    https://www.cnblogs.com/lay2017/p/12901123.html

    正文

    SocketChannel表示一个连接到TCP通道的Socket上。有两种方式可以创建SocketChannel

    1.你可以直接open一个SocketChannel,然后connect

    2.当ServerSocketChannel接收到连接的时候

    open一个SocketChannel

    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));

    close一个SocketChannel

    socketChannel.close(); 

    从SocketChannel读取数据

    ByteBuffer buf = ByteBuffer.allocate(48);
    
    int bytesRead = socketChannel.read(buf);

    写入数据到SocketChannel

    String newData = "New String to write to file..." + System.currentTimeMillis();
    
    ByteBuffer buf = ByteBuffer.allocate(48);
    buf.clear();
    buf.put(newData.getBytes());
    
    buf.flip();
    
    while(buf.hasRemaining()) {
        channel.write(buf);
    }

    非阻塞模式

    你可以将SocketChannel设置为非阻塞模式。在非阻塞模式下,connect、read、write操作都变成了异步

    connect

    非阻塞模式下,connect方法变成异步。你需要主动去判断连接是否完成

    socketChannel.configureBlocking(false);
    socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
    
    while(! socketChannel.finishConnect() ){
        //wait, or do something else...    
    }

    write

    非阻塞模式下,write方法直接返回。因此,你需要在循环中不断调用write方法。但是在上面的write示例中本身就是循环调用,所以其实写法没有不同

    read

    非阻塞模式下,read方法直接返回,这时候可能并未读取到任何数据。因此,你需要注意read方法返回值,从而判断当前有没有读取到数据。

    非阻塞模式下的选择器

    非阻塞模式的SocketChannel和Selector搭配使用非常方便。通过将SocketChannel注册到Selector中,当SocketChannel可用的时候通过事件响应异步处理

  • 相关阅读:
    949. Largest Time for Given Digits
    450. Delete Node in a BST
    983. Minimum Cost For Tickets
    16. 3Sum Closest java solutions
    73. Set Matrix Zeroes java solutions
    347. Top K Frequent Elements java solutions
    215. Kth Largest Element in an Array java solutions
    75. Sort Colors java solutions
    38. Count and Say java solutions
    371. Sum of Two Integers java solutions
  • 原文地址:https://www.cnblogs.com/lay2017/p/12906661.html
Copyright © 2020-2023  润新知