为什么我应该在写入数据之前检查通道isWritable()

时间:2017-05-09 04:59:39

标签: java nio

我在服务器端使用ServerSocket频道(NIO)。我的问题是,如果在将数据写入客户端之前不检查套接字通道是否可写,会发生什么?我测试了一个服务器程序,该程序工作正常,没有检查通道是否准备就绪。

public class SelectorExample {  
    public static void main (String [] args)
            throws IOException {
    // Get selector
    Selector selector = Selector.open();

    System.out.println("Selector open: " + selector.isOpen());

    // Get server socket channel and register with selector
    ServerSocketChannel serverSocket = ServerSocketChannel.open();
    //serverSocket.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    InetSocketAddress hostAddress = new InetSocketAddress("localhost", 5454);
    serverSocket.socket().bind(hostAddress,0);
    serverSocket.configureBlocking(false);
    int ops = serverSocket.validOps();
    SelectionKey selectKy = serverSocket.register(selector, ops, null);

    for (;;) {

       System.out.println("Waiting for select...");

        int noOfKeys = selector.select();         

        Set selectedKeys = selector.selectedKeys();
        Iterator iter = selectedKeys.iterator();

        while (iter.hasNext()) {

            SelectionKey ky = (SelectionKey)iter.next();

                ++count;
            if (ky.isAcceptable()) {
                // Accept the new client connection
                SocketChannel client = serverSocket.accept();
                client.configureBlocking(false);

                // Add the new connection to the selector
              client.register(selector, SelectionKey.OP_READ);

               System.out.println("["+new java.sql.Timestamp(System.currentTimeMillis())+"]"+"Accepted new connection from client: " + client);

            }
            else if (ky.isReadable()) {                 
                // Read the data from client

                SocketChannel client = (SocketChannel) ky.channel();
                ByteBuffer buffer = ByteBuffer.allocate(2048);
                int i =client.read(buffer);
                String output = new String(buffer.array());                 
                    System.out.println("Message read from client: " + output);
                output =output.trim();
                output=output+"\r\n";                

                //*********write message here******
                byte[] a=output.getBytes();
                ByteBuffer bb=ByteBuffer.wrap(a);
                 client.write(bb);                   

                  buffer.clear();
                 System.out.println("   Sent    Message ");
                if (i == -1) {                  
                    client.close();
                   System.out.println("Client messages are complete; close.");
                }

            } // end if (ky...)
            //countkey++;
            iter.remove();                  
        } // end while loop

    } // end for loop
}

}

1 个答案:

答案 0 :(得分:1)

  

为什么我应该在写之前检查频道isWritable()

没有什么可以说你应该。

  

如果在将数据写入客户端之前没有检查socketchannel是否可写,会发生什么?

您可能会获得零长度写入。你可能会写一篇简短的文章。

一般来说,只要你有东西要写,你就应该写,只有使用OP_WRITE ,如果你写了零或短。在isWritable()之前你不能写的任何想法都是错误的。