SocketChannel和ServerSocketChannel


SocketChannel

1. SocketChannel概述

Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道。可以通过以下2种方式创建SocketChannel:

  1. 打开一个SocketChannel并连接到互联网上的某台服务器。
  2. 一个新连接到达ServerSocketChannel时,会创建一个SocketChannel。

 

1.1 打开 SocketChannel

下面是SocketChannel的打开方式:

 

SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));

 

1.2 关闭 SocketChannel

当用完SocketChannel之后调用SocketChannel.close()关闭SocketChannel:

 

socketChannel.close();

 

1.3 SocketChannel读取数据

要从SocketChannel中读取数据,调用一个read()的方法之一。以下是例子:

 

ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = socketChannel.read(buf);

 

首先,分配一个Buffer。从SocketChannel读取到的数据将会放到这个Buffer中。

然后,调用SocketChannel.read()。该方法将数据从SocketChannel 读到Buffer中。read()方法返回的int值表示读了多少字节进Buffer里。如果返回的是-1,表示已经读到了流的末尾(连接关闭了)。

1.4 SocketChannel写入数据

写数据到SocketChannel用的是SocketChannel.write()方法,该方法以一个Buffer作为参数。示例如下:

 

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); }

 

注意SocketChannel.write()方法的调用是在一个while循环中的。Write()方法无法保证能写多少字节到SocketChannel。所以,我们重复调用write()直到Buffer没有要写的字节为止。

2. SocketChannel非阻塞模式

可以设置 SocketChannel 为非阻塞模式(non-blocking mode).设置之后,就可以在异步模式下调用connect(), read() 和write()了。

2.1 connect()

如果SocketChannel在非阻塞模式下,此时调用connect(),该方法可能在连接建立之前就返回了。为了确定连接是否建立,可以调用finishConnect()的方法。像这样:

 

socketChannel.configureBlocking(false); socketChannel.connect(new InetSocketAddress("http://jenkov.com", 80));  while(! socketChannel.finishConnect() ){  //wait, or do something else... }

 

2.2 write()

非阻塞模式下,write()方法在尚未写出任何内容时可能就返回了。所以需要在循环中调用write()。前面已经有例子了,这里就不赘述了。

2.3 read()

非阻塞模式下,read()方法在尚未读取到任何数据时可能就返回了。所以需要关注它的int返回值,它会告诉你读取了多少字节。

3. SocketChannel非阻塞模式

非阻塞模式与选择器搭配会工作的更好,通过将一或多个SocketChannel注册到Selector,可以询问选择器哪个通道已经准备好了读取,写入等。Selector与SocketChannel的搭配使用会在后面详讲

 

 

ServerSocketChannel

1.ServerSocketChannel概述

Java NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道, 就像标准IO中的ServerSocket一样。ServerSocketChannel类在 java.nio.channels包中

 

1.1 打开 ServerSocketChannel

通过调用 ServerSocketChannel.open() 方法来打开ServerSocketChannel.如:

 

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

 

1.2 关闭 ServerSocketChannel

通过调用ServerSocketChannel.close() 方法来关闭ServerSocketChannel. 如:

 

serverSocketChannel.close();

1.3 监听新进来的连接

通过 ServerSocketChannel.accept() 方法监听新进来的连接。当 accept()方法返回的时候,它返回一个包含新进来的连接的 SocketChannel。因此, accept()方法会一直阻塞到有新连接到达。

通常不会仅仅只监听一个连接,在while循环中调用 accept()方法. 如下面的例子:

 

while(true){  SocketChannel socketChannel =  serverSocketChannel.accept();   //do something with socketChannel... }

当然,也可以在while循环中使用除了true以外的其它退出准则。

2. ServerSocketChannel非阻塞模式

ServerSocketChannel可以设置成非阻塞模式。在非阻塞模式下,accept() 方法会立刻返回,如果还没有新进来的连接,返回的将是null。 因此,需要检查返回的SocketChannel是否是null

 

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  serverSocketChannel.socket().bind(new InetSocketAddress(9999)); serverSocketChannel.configureBlocking(false);  while(true){  SocketChannel socketChannel =  serverSocketChannel.accept();   if(socketChannel != null){  //do something with socketChannel...  } }

 

SocketChannel示例

 

如下是一个ServerSocketChannel的示例,注意需要先启动ServerSocketChannel

 

@Test  public void test2() throws IOException {  ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  serverSocketChannel.socket().bind(new InetSocketAddress(9999));  serverSocketChannel.configureBlocking(false);  ByteBuffer buf = ByteBuffer.allocate(256);  while(true){  SocketChannel socketChannel =  serverSocketChannel.accept();  if(socketChannel != null){  int bytesRead = socketChannel.read(buf);  while(bytesRead>0){  buf.flip();  while(buf.hasRemaining()){  System.out.print((char)buf.get());  }  System.out.println();  buf.clear();  bytesRead = socketChannel.read(buf);  }  }  }  }

 

如下是一个SocketChannel 的示例

@Test  public void test1() throws IOException, InterruptedException {  SocketChannel socketChannel = SocketChannel.open();  //设置为NIO  socketChannel.configureBlocking(false);  socketChannel.connect(new InetSocketAddress("localhost", 9999));  ByteBuffer buf = ByteBuffer.allocate(256);  if(socketChannel.finishConnect())  {  int i=0;  while(true)  {  TimeUnit.SECONDS.sleep(1);  String info = "I'm "+i+++"-th information from client";  buf.clear();  buf.put(info.getBytes());  buf.flip();  while(buf.hasRemaining()){  socketChannel.write(buf);  }  }  }  }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM