Java Nio 简明教程

Java NIO - ServerSocket Channel

Java NIO 服务器套接字通道是再次用于流式数据流连接套接字的可选择类型通道。服务器套接字通道可通过唤起其静态` open() 方法(在没有预先存在套接字的情况下提供)进行创建。通过唤起开放方法创建服务器套接字通道,但还未绑定。为了绑定套接字通道,需要调用 bind() `方法。

Java NIO server socket channel is again a selectable type channel used for stream oriented data flow connecting sockets.Server Socket channel can be created by invoking its static open() method,providing any pre-existing socket is not already present.Server Socket channel is created by invoking open method but not yet bound.In order to bound socket channel bind() method is to be called.

这里需要提到的一点是,如果通道没有绑定,并且尝试进行任何 I/O 操作,则此通道会抛出 NotYetBoundException。因此,在执行任何 IO 操作之前,必须确保通道已绑定。

One point to be mentioned here is if channel is not bound and any I/O operation is tried to be attempted then NotYetBoundException is thrown by this channel.So one must be ensure that channel is bounded before performing any IO operation.

通过调用 ServerSocketChannel.accept() 方法监听服务器套接字通道的传入连接。当 accept() 方法返回时,它会返回具有传入连接的 SocketChannel。因此,accept() 方法会一直阻止,直到传入连接到达为止。如果通道处于非阻塞模式,那么在没有挂起连接的情况下,accept 方法会立即返回 null。否则,它会无限期阻止,直到有可用的新连接或发生 I/O 错误。

Incoming connections for the server socket channel are listen by calling the ServerSocketChannel.accept() method. When the accept() method returns, it returns a SocketChannel with an incoming connection. Thus, the accept() method blocks until an incoming connection arrives.If the channel is in non-blocking mode then accept method will immediately return null if there are no pending connections. Otherwise it will block indefinitely until a new connection is available or an I/O error occurs.

新通道的套接字最初未绑定;必须通过其套接字的绑定方法之一将其绑定到特定地址,才能接受连接。新通道也可以通过唤起系统范围的默认 SelectorProvider 对象的 openServerSocketChannel 方法进行创建。

The new channel’s socket is initially unbound; it must be bound to a specific address via one of its socket’s bind methods before connections can be accepted.Also the new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.

与套接字通道类似,服务器套接字通道可以使用` read() `方法读取数据。首先分配缓冲区。从 ServerSocketChannel 读入的数据存储在缓冲区中。其次,我们调用 ServerSocketChannel.read() 方法,它将数据从 ServerSocketChannel 读入缓冲区。read() 方法的整数值返回写入缓冲区的字节数。

Like socket channel server socket channel could read data using read() method.Firstly the buffer is allocated. The data read from a ServerSocketChannel is stored into the buffer.Secondly we call the ServerSocketChannel.read() method and it reads the data from a ServerSocketChannel into a buffer. The integer value of the read() method returns how many bytes were written into the buffer

同样地,可以使用` write() `方法将数据写入服务器套接字通道,并使用缓冲区作为参数。通常在 while 循环中使用 write 方法,因为需要重复 write() 方法,直到缓冲区中没有可写入的可用字节为止。

Similarly data could be written to server socket channel using write() method using buffer as a parameter.Commonly uses write method in a while loop as need to repeat the write() method until the Buffer has no further bytes available to write.

Important methods of Socket channel

  1. bind(SocketAddress local) − This method is used to bind the socket channel to the local address which is provided as the parameter to this method.

  2. accept() − This method is used to accepts a connection made to this channel’s socket.

  3. connect(SocketAddress remote) − This method is used to connect the socket to the remote address.

  4. finishConnect() − This method is used to finishes the process of connecting a socket channel.

  5. getRemoteAddress() − This method return the address of remote location to which the channel’s socket is connected.

  6. * isConnected()* − As already mentioned this method returns the status of connection of socket channel i.e whether it is connected or not.

  7. open() − Open method is used open a socket channel for no specified address.This convenience method works as if by invoking the open() method, invoking the connect method upon the resulting server socket channel, passing it remote, and then returning that channel.

  8. read(ByteBuffer dst) − This method is used to read data from the given buffer through socket channel.

  9. setOption(SocketOption<T> name, T value) − This method sets the value of a socket option.

  10. socket() − This method retrieves a server socket associated with this channel.

  11. validOps() − This method returns an operation set identifying this channel’s supported operations.Server-socket channels only support the accepting of new connections, so this method returns SelectionKey.OP_ACCEPT.

Example

以下示例显示如何从 Java NIO ServerSocketChannel 发送数据。

The following example shows the how to send data from Java NIO ServerSocketChannel.

C:/Test/temp.txt

Hello World!

Client: SocketChannelClient.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.EnumSet;

public class SocketChannelClient {
   public static void main(String[] args) throws IOException {
      ServerSocketChannel serverSocket = null;
      SocketChannel client = null;
      serverSocket = ServerSocketChannel.open();
      serverSocket.socket().bind(new InetSocketAddress(9000));
      client = serverSocket.accept();
      System.out.println("Connection Set:  " + client.getRemoteAddress());
      Path path = Paths.get("C:/Test/temp1.txt");
      FileChannel fileChannel = FileChannel.open(path,
         EnumSet.of(StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING,
            StandardOpenOption.WRITE)
         );
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while(client.read(buffer) > 0) {
         buffer.flip();
         fileChannel.write(buffer);
         buffer.clear();
      }
      fileChannel.close();
      System.out.println("File Received");
      client.close();
   }
}

Output

在服务器启动前运行客户端不会打印任何内容。

Running the client will not print anything until server starts.

Server: SocketChannelServer.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SocketChannelServer {
   public static void main(String[] args) throws IOException {
      SocketChannel server = SocketChannel.open();
      SocketAddress socketAddr = new InetSocketAddress("localhost", 9000);
      server.connect(socketAddr);
      Path path = Paths.get("C:/Test/temp.txt");
      FileChannel fileChannel = FileChannel.open(path);
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      while(fileChannel.read(buffer) > 0) {
         buffer.flip();
         server.write(buffer);
         buffer.clear();
      }
      fileChannel.close();
      System.out.println("File Sent");
      server.close();
   }
}

Output

运行服务器将打印以下内容。

Running the server will print the following.

Connection Set:  /127.0.0.1:49558
File Received