Using the URLConnection class withbuffers and channels

2023. 2. 14. 14:08자바

try {
        URL url = new URL("http://www.google.com");
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        ReadableByteChannel channel = Channels.newChannel(inputStream);
        ByteBuffer buffer = ByteBuffer.allocate(64);
        String line = null;
        while (channel.read(buffer) > 0) {System.out.println(new String(buffer.array()));
            buffer.clear();
        }
        channel.close();
    }
catch (IOException ex) {
        // Handle exceptions
        }

 

바이트를 읽어낼 수가 있는 채널인 ReadableByteChannel 인스턴스를 생성합니다.

이 인스턴스는 read 메서드를 통해 사이트에서 읽을 수 있습니다.

 

이후 ByteBuffer를 생성합니다.

ByteBuffer는 바이트 데이터를 저장하고 읽는 저장소입니다.

배열을 멤버변수로 가지고 있고, 배열에 대한 읽기/쓰기를 지원합니다.

 

ByteBuffer 인스턴스는 채널에서 데이터를 수신하고 read 메서드의 인자로서로서 사용됩니다.

버퍼는 64바이트를 가지고 있습니다.

read 메서드는 읽은 바이트의 수를 리턴합니다.

 

ByteBuffer class의 array 메서드는 바이트의 배열을 리턴합니다.

그리고 String class 생성자의 인자로 사용됩니다. 이것은 읽은 데이터를 나타내는 데 사용됩니다.

 

clear method는 버퍼를 재설정하는 데 사용됩니다.

 

 

'자바' 카테고리의 다른 글

Creating a simple echo server  (0) 2023.02.14
The client/server architecture  (0) 2023.02.14
Using the URLConnection class  (0) 2023.02.14
NIO support  (0) 2023.02.14
Network addressing using the InetAddress class  (0) 2023.02.14