1、步驟
(1)建立SocketChannel實例,並將其配置為非阻塞模式,只有在SocketChannel實例中,任何I/O操作都是非阻塞的。
(2)使用connect()方法連接伺服器,同時使用while循環連續偵測和完全連接。在需要立即進行I/O操作之前,必須使用finishConnect()來完成連線程序。
(3)用ByteBuffer讀寫字節,假如SelectableChannel是一種非阻塞模式,那麼它的I/O操作讀寫字節可能比實際字節少,甚至沒有。因此,我們使用循環連續的讀寫來確保讀寫完成。
2、實例
public class NonBlockingTCPClient { public static void main(String[] args) { byte[] data = "hello".getBytes(); SocketChannel channel = null; try { // 1. open a socket channel channel = SocketChannel.open(); // adjust to be nonblocking channel.configureBlocking(false); // 2. init connection to server and repeatedly poll with complete // connect() and finishConnect() are nonblocking operation, both return immediately if (!channel.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8899))) { while (!channel.finishConnect()) { System.out.print("."); } } System.out.println("Connected to server..."); ByteBuffer writeBuffer = ByteBuffer.wrap(data); ByteBuffer readBuffer = ByteBuffer.allocate(data.length); int totalBytesReceived = 0; int bytesReceived; // 3. read and write bytes while (totalBytesReceived < data.length) { if (writeBuffer.hasRemaining()) { channel.write(writeBuffer); } if ((bytesReceived = channel.read(readBuffer)) == -1) { throw new SocketException("Connection closed prematurely"); } totalBytesReceived += bytesReceived; System.out.print("."); } System.out.println("Server said: " + new String(readBuffer.array())); } catch (IOException e) { e.printStackTrace(); } finally { // 4 .close socket channel try { if (channel != null) { channel.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
以上是SocketChannel在java中如何實現客戶端的詳細內容。更多資訊請關注PHP中文網其他相關文章!