Home  >  Article  >  Java  >  How to implement SocketChannel client in java

How to implement SocketChannel client in java

王林
王林forward
2023-04-17 22:28:011408browse

1. Steps

(1) Create a SocketChannel instance and configure it in non-blocking mode. Only in the SocketChannel instance, any I/O operations are non-blocking.

(2) Use the connect() method to connect to the server, and use a while loop to continuously detect and complete the connection. You must use finishConnect() to complete the connection process before immediate I/O operations are required.

(3) Use ByteBuffer to read and write bytes. If SelectableChannel is in a non-blocking mode, then its I/O operation may read and write fewer bytes than the actual bytes, or even none. Therefore, we use continuous reading and writing in a loop to ensure that the reading and writing are completed.

2. Example

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

The above is the detailed content of How to implement SocketChannel client in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete