9, Java NIO SocketChannel
SocketChannel
can be created: SocketChannel
and connect to a server somewhere on the internet. SocketChannel
can be created when an incoming connection arrives at a ServerSocketChannel
. Opening a SocketChannel
Here is how you open a
SocketChannel
: SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
Closing a SocketChannel
You close a
SocketChannel
after use by calling the SocketChannel.close()
method. Here is how that is done: socketChannel.close();
Reading from a SocketChannel
To read data from a
SocketChannel
you call one of the read()
methods. Here is an example: ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(buf);
First a
Buffer
is allocated. The data read from the SocketChannel
is read into the Buffer
. Second the
SocketChannel.read()
method is called. This method reads data from the SocketChannel
into the Buffer
. The int
returned by the read()
method tells how many bytes were witten into the Buffer
. If -1 is returned, the end-of-stream is reached (the connection is closed).
Writing to a SocketChannel
Writing data to a
SocketChannel
is done using the SocketChannel.write()
method, which takes a Buffer
as parameter. Here is an example: String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
channel.write(buf);
}
Notice how the
SocketChannel.write()
method is called inside a while-loop. There is no guarantee of how many bytes the write()
method writes to the SocketChannel
. Therefore we repeat the write()
call until the Buffer
has no further bytes to write. Non-blocking Mode
You can set a
SocketChannel
into non-blocking mode. When you do so, you can call connect()
, read()
and write()
in asynchronous mode. connect()
If the
SocketChannel
is in non-blocking mode, and you call connect()
, the method may return before a connection is established. To determine whether the connection is established, you can call the finishConnect()
method, like this: socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));
while(! socketChannel.finishConnect() ){
//wait, or do something else...
}
write()
In non-blocking mode the
write()
method may return without having written anything. Therefore you need to call the write()
method in a loop. But, since this is already being done in the previous write examples, no need to do anything differently here. read()
In non-blocking mode the
read()
method may return without having read any data at all. Therefore you need to pay attention to the returned int
, which tells how many bytes were read. Non-blocking Mode with Selectors
The non-blocking mode of
SocketChannel
's works much better with Selector
's. By registering one or more SocketChannel
's with a Selector
, you can ask the Selector
for channels that are ready for reading, writing etc. How to use Selector
's with SocketChannel
's is explained in more detail in a later text in this tutorial.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.