Home  >  Article  >  Java  >  JAVA-7NIO之Socket/ServerSocket Channel

JAVA-7NIO之Socket/ServerSocket Channel

巴扎黑
巴扎黑Original
2017-06-26 09:58:011001browse

1. ServerSocketChannel

ServerSocketChannel in Java NIO is a channel that can monitor new incoming TCP connections, just like ServerSocket in standard IO. The ServerSocketChannel class is in the java.nio.channels package.

Open ServerSocketChannel

Open ServerSocketChannel by calling ServerSocketChannel.open() method.

Close ServerSocketChannel

Close it by calling ServerSocketChannel.close() method ServerSocketChannel.

Listen to new incoming connections

Listen to new incoming connections through the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel containing the new incoming connection. Therefore, the accept() method will block until a new connection arrives.

Usually you don't just listen to one connection and call the accept() method in the while loop.

Of course, you can also use other exit criteria besides true in the while loop.

Non-blocking mode

ServerSocketChannel can be set to non-blocking mode. In non-blocking mode, the accept() method will return immediately. If there is no new incoming connection, the return value will be null. Therefore, you need to check whether the returned SocketChannel is null. For example:

    /** * socket server channel     */@Testpublic void text2() throws IOException {
        ServerSocketChannel channel = ServerSocketChannel.open();    //新建channelchannel.socket().bind(new InetSocketAddress(9999));     //监听端口channel.configureBlocking(true);                             //设置阻塞while (true) {
            SocketChannel accept = channel.accept();                    //设置为阻塞,则此方法阻塞,直到有连接//如果设置为非阻塞,需要在这里判断 accept == null?ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            accept.read(byteBuffer);
            byteBuffer.flip();                                    //反转while (byteBuffer.hasRemaining()) {                   //判断System.err.println((char)byteBuffer.get());       //输出            }
        }
    }

2. SocketChannel

The SocketChannel in Java NIO is a connection to A channel for TCP network sockets. SocketChannel can be created in the following 2 ways:

  1. Open a SocketChannel and connect to a server on the Internet.

  2. When a new connection arrives at ServerSocketChannel, a SocketChannel is created.

Open SocketChannel

The following is how to open SocketChannel:

Close SocketChannel

Call SocketChannel.close when you are finished with SocketChannel () Close SocketChannel:

Read data from SocketChannel

To read data from SocketChannel, call one of the read() methods.

First, allocate a Buffer. The data read from SocketChannel will be placed in this Buffer.

Then, call SocketChannel.read(). This method reads data from SocketChannel into Buffer. The int value returned by the read() method indicates how many bytes were read into the Buffer. If -1 is returned, it means that the end of the stream has been read (the connection was closed).

Write to SocketChannel

Writing data to SocketChannel uses the SocketChannel.write() method, which takes a Buffer as a parameter.

Note that the SocketChannel.write() method is called in a while loop. The Write() method cannot guarantee how many bytes can be written to the SocketChannel. So, we call write() repeatedly until the Buffer has no bytes left to write.

Non-blocking mode

You can set SocketChannel to non-blocking mode (non-blocking mode). After setting, you can call connect(), read() and write() in asynchronous mode .

connect()

If SocketChannel is in non-blocking mode and connect() is called at this time, the method may return before the connection is established. To determine whether the connection is established, you can call the finishConnect() method.

write()

In non-blocking mode, the write() method may return before any content has been written. So write() needs to be called in the loop. There have been examples before, so I won’t go into details here.

read()

In non-blocking mode, the read() method may return before any data has been read. So you need to pay attention to its int return value, which will tell you how many bytes were read.

Non-blocking mode and selector

Non-blocking mode will work better with a selector. By registering one or more SocketChannels to the Selector, you can ask the selector which channel is ready. Ok reading, writing etc. The combination of Selector and SocketChannel will be discussed in detail later.

/** * socket channel     */@Testpublic void test3() throws IOException {
        SocketChannel channel = SocketChannel.open();                               //新建服务端channel.connect(new InetSocketAddress("127.0.0.1",9999));   //连接服务端地址ByteBuffer byteBuffer = ByteBuffer.allocate(1024);  //缓冲区byteBuffer.put("123".getBytes());
        byteBuffer.flip();                                  //反转while (byteBuffer.hasRemaining()) {                 //判断            channel.write(byteBuffer);
        }
    }

The above is the detailed content of JAVA-7NIO之Socket/ServerSocket Channel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn