首頁  >  文章  >  Java  >  如何使用Java中的SocketChannel進行網路通訊?

如何使用Java中的SocketChannel進行網路通訊?

WBOY
WBOY轉載
2023-04-24 09:58:061273瀏覽

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;
    }

以上是如何使用Java中的SocketChannel進行網路通訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除