>  기사  >  Java  >  Java에서 SocketChannel 클라이언트를 구현하는 방법

Java에서 SocketChannel 클라이언트를 구현하는 방법

王林
王林앞으로
2023-04-17 22:28:011408검색

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

위 내용은 Java에서 SocketChannel 클라이언트를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제