首页 > 文章列表 > Java SocketChannel的使用方法及示例

Java SocketChannel的使用方法及示例

java SocketChannel
377 2023-04-27

1、说明

SocketChannel代表套接字通道,实例是通过其静态方法创建的。

SocketChannel是SelectableChannel的子类,假如没有配置阻塞模式,那么SocketChannel对象默认为阻塞模式,那么open(SocketAddressremote)的方法实际上就是阻塞打开服务器连接。而SocketChannel上的任何I/O操作都是阻塞的。

2、实例

    public static SocketChannel open() throws IOException {
        return SelectorProvider.provider().openSocketChannel();
    }
 
    public static SocketChannel open(SocketAddress remote)
        throws IOException
    {
        // 1. ceate socket channel
        SocketChannel sc = open();
        try {
            // 2. connect channel's socket, blocking until connected or error
            sc.connect(remote);
        } catch (Throwable x) {
            try {
                sc.close();
            } catch (Throwable suppressed) {
                x.addSuppressed(suppressed);
            }
            throw x;
        }
        assert sc.isConnected();
        return sc;
    }