e173. creating a non-blocking socket.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 30 行

TXT
30 行
字号
This example shows how to create a non-blocking socket. A non-blocking socket requires a socket channel. 
See also e176 Using a Selector to Manage Non-Blocking Sockets. 

    // Creates a non-blocking socket channel for the specified host name and port.
    // connect() is called on the new channel before it is returned.
    public static SocketChannel createSocketChannel(String hostName, int port) throws IOException {
        // Create a non-blocking socket channel
        SocketChannel sChannel = SocketChannel.open();
        sChannel.configureBlocking(false);
    
        // Send a connection request to the server; this method is non-blocking
        sChannel.connect(new InetSocketAddress(hostName, port));
        return sChannel;
    }

    // Create a non-blocking socket and check for connections
    try {
        // Create a non-blocking socket channel on port 80
        SocketChannel sChannel = createSocketChannel("hostname.com", 80);
    
        // Before the socket is usable, the connection must be completed
        // by calling finishConnect(), which is non-blocking
        while (!sChannel.finishConnect()) {
            // Do something else
        }
        // Socket channel is now ready to use
    } catch (IOException e) {
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?