Netty Quick Start (04) Java NIO introduced -Channel

Channel (channel) Introduction

All operations begin NIO channel, the data channel is the destination or source of data writing, the following mainly Channel, the java.nio package Main achieved:

file

FileChannel: file path, the file for read and write

DatagramChannel: means for receiving and sending the UDP connection

SocketChannel: I understand it as a TCP connection channel, simple to understand TCP client

ServerSocketChannel: TCP corresponding server, listening on a port for incoming requests

Channel concept needs to know is that the channel is to read data from the read channel buffer inside,

file

Channel write data from the buffer is to be written in the channel,

file

This order must be clear. In fact, the channel can be understood as a connector, and the channel is bidirectional, readable and writable. Behind network channel will be dedicated to the presentation, following a presentation file channel.

File channel -FileChannel

Let's look at an example of a copy of a file, first define the copy source file and the copy destination:

file

This time the destination is not content:

file

Then read the file to a stream, then the acquisition channel stream:

file

With the channel later, whether read or write buffer is required to create a buffer zone the following:

file

Copying operation starts following:

file

Program logic is simple, each read 1024, read from the source file into the target directory files, read the exit, pay attention to convert the intermediate read-write mode. Note that the start time for fromFileChannel read operation is read from the channel to the buffer, the buffer at this time is for a write operation, data is written from fromFileChannel buffer.

While the back of the copy is for toFileChannel write operation, data is written from the channel buffer of the object file. For the buffer at a time is read, the data buffer is read.

As can be seen from the above buffer as a buffer between the two channels is truly.

Code address: https: //gitee.com/blueses/netty-demo 03

This article from the blog article multiple platforms OpenWrite release!

Guess you like

Origin juejin.im/post/5e1c2268e51d4501fa467b96