Java Socket编程实例(四)- NIO TCP实践

 更新时间:2016年06月15日 09:52:59   作者:kingxss  
这篇文章主要讲解Java Socket编程中NIO TCP的实例,希望能给大家做一个参考。

一、回传协议接口和TCP方式实现:

1.接口:

import java.nio.channels.SelectionKey; 
import java.io.IOException; 
 
public interface EchoProtocol { 
 void handleAccept(SelectionKey key) throws IOException; 
 void handleRead(SelectionKey key) throws IOException; 
 void handleWrite(SelectionKey key) throws IOException; 
} 

2.实现:

import java.nio.channels.*; 
import java.nio.ByteBuffer; 
import java.io.IOException; 
 
public class TCPEchoSelectorProtocol implements EchoProtocol{ 
  private int bufSize; // Size of I/O buffer 
 
  public EchoSelectorProtocol(int bufSize) { 
    this.bufSize = bufSize; 
  } 
 
  public void handleAccept(SelectionKey key) throws IOException { 
    SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept(); 
    clntChan.configureBlocking(false); // Must be nonblocking to register 
    // Register the selector with new channel for read and attach byte buffer 
    clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufSize)); 
     
  } 
 
  public void handleRead(SelectionKey key) throws IOException { 
    // Client socket channel has pending data 
    SocketChannel clntChan = (SocketChannel) key.channel(); 
    ByteBuffer buf = (ByteBuffer) key.attachment(); 
    long bytesRead = clntChan.read(buf); 
    if (bytesRead == -1) { // Did the other end close? 
      clntChan.close(); 
    } else if (bytesRead > 0) { 
      // Indicate via key that reading/writing are both of interest now. 
      key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); 
    } 
  } 
 
  public void handleWrite(SelectionKey key) throws IOException { 
    /* 
     * Channel is available for writing, and key is valid (i.e., client channel 
     * not closed). 
     */ 
    // Retrieve data read earlier 
    ByteBuffer buf = (ByteBuffer) key.attachment(); 
    buf.flip(); // Prepare buffer for writing 
    SocketChannel clntChan = (SocketChannel) key.channel(); 
    clntChan.write(buf); 
    if (!buf.hasRemaining()) { // Buffer completely written?  
      //Nothing left, so no longer interested in writes 
      key.interestOps(SelectionKey.OP_READ); 
    } 
    buf.compact(); // Make room for more data to be read in 
  } 
 
} 

二、NIO TCP客户端:

import java.net.InetSocketAddress; 
import java.net.SocketException; 
import java.nio.ByteBuffer; 
import java.nio.channels.SocketChannel; 
 
public class TCPEchoClientNonblocking { 
 
  public static void main(String args[]) throws Exception { 
    String server = "127.0.0.1"; // Server name or IP address 
    // Convert input String to bytes using the default charset 
    byte[] argument = "0123456789abcdefghijklmnopqrstuvwxyz".getBytes(); 
 
    int servPort = 5500; 
 
    // Create channel and set to nonblocking 
    SocketChannel clntChan = SocketChannel.open(); 
    clntChan.configureBlocking(false); 
 
    // Initiate connection to server and repeatedly poll until complete 
    if (!clntChan.connect(new InetSocketAddress(server, servPort))) { 
      while (!clntChan.finishConnect()) { 
        System.out.print("."); // Do something else 
      } 
    } 
    ByteBuffer writeBuf = ByteBuffer.wrap(argument); 
    ByteBuffer readBuf = ByteBuffer.allocate(argument.length); 
    int totalBytesRcvd = 0; // Total bytes received so far 
    int bytesRcvd; // Bytes received in last read 
    while (totalBytesRcvd < argument.length) { 
      if (writeBuf.hasRemaining()) { 
        clntChan.write(writeBuf); 
      } 
      if ((bytesRcvd = clntChan.read(readBuf)) == -1) { 
        throw new SocketException("Connection closed prematurely"); 
      } 
      totalBytesRcvd += bytesRcvd; 
      System.out.print("."); // Do something else 
    } 
 
    System.out.println("Received: " + // convert to String per default charset 
        new String(readBuf.array(), 0, totalBytesRcvd).length()); 
    clntChan.close(); 
  } 
} 

三、NIO TCP服务端:

import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.nio.channels.*; 
import java.util.Iterator; 
 
public class TCPServerSelector { 
  private static final int BUFSIZE = 256; // Buffer size (bytes) 
  private static final int TIMEOUT = 3000; // Wait timeout (milliseconds) 
   
  public static void main(String[] args) throws IOException { 
    int[] ports = {5500}; 
    // Create a selector to multiplex listening sockets and connections 
    Selector selector = Selector.open(); 
 
    // Create listening socket channel for each port and register selector 
    for (int port : ports) { 
      ServerSocketChannel listnChannel = ServerSocketChannel.open(); 
      listnChannel.socket().bind(new InetSocketAddress(port)); 
      listnChannel.configureBlocking(false); // must be nonblocking to register 
      // Register selector with channel. The returned key is ignored 
      listnChannel.register(selector, SelectionKey.OP_ACCEPT); 
    } 
 
    // Create a handler that will implement the protocol 
    TCPProtocol protocol = new TCPEchoSelectorProtocol(BUFSIZE); 
 
    while (true) { // Run forever, processing available I/O operations 
      // Wait for some channel to be ready (or timeout) 
      if (selector.select(TIMEOUT) == 0) { // returns # of ready chans 
        System.out.print("."); 
        continue; 
      } 
 
      // Get iterator on set of keys with I/O to process 
      Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator(); 
      while (keyIter.hasNext()) { 
        SelectionKey key = keyIter.next(); // Key is bit mask 
        // Server socket channel has pending connection requests? 
        if (key.isAcceptable()) { 
          System.out.println("----accept-----"); 
          protocol.handleAccept(key); 
        } 
        // Client socket channel has pending data? 
        if (key.isReadable()) { 
          System.out.println("----read-----"); 
          protocol.handleRead(key); 
        } 
        // Client socket channel is available for writing and  
        // key is valid (i.e., channel not closed)? 
        if (key.isValid() && key.isWritable()) { 
          System.out.println("----write-----"); 
          protocol.handleWrite(key); 
        } 
        keyIter.remove(); // remove from set of selected keys 
      } 
    } 
  } 
   
} 

以上就是本文的全部内容,查看更多Java的语法,大家可以关注:《Thinking in Java 中文手册》、《JDK 1.7 参考手册官方英文版》、《JDK 1.6 API java 中文参考手册》、《JDK 1.5 API java 中文参考手册》,也希望大家多多支持脚本之家。

相关文章

  • Java使用DualPivotQuicksort排序

    Java使用DualPivotQuicksort排序

    这篇文章主要介绍了Java使用DualPivotQuicksort排序,喜欢算法的同学一定要看一下
    2021-04-04
  • SpringBoot+Redis执行lua脚本的方法步骤

    SpringBoot+Redis执行lua脚本的方法步骤

    这篇文章主要介绍了SpringBoot+Redis执行lua脚本的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • Springboot中Instant时间传参及序列化详解

    Springboot中Instant时间传参及序列化详解

    这篇文章主要介绍了Springboot中Instant时间传参及序列化详解,Instant是Java8引入的一个精度极高的时间类型,可以精确到纳秒,但实际使用的时候不需要这么高的精确度,通常到毫秒就可以了,需要的朋友可以参考下
    2023-11-11
  • 基于springboot2集成jpa,创建dao的案例

    基于springboot2集成jpa,创建dao的案例

    这篇文章主要介绍了基于springboot2集成jpa,创建dao的案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-01-01
  • springboot接收日期类型参数的操作方法

    springboot接收日期类型参数的操作方法

    如果使用Get请求,直接使用对象接收,则可以使用@DateTimeFormat注解进行格式化,本文重点给大家介绍springboot接收日期类型参数的方法,感兴趣的朋友一起看看吧
    2024-02-02
  • Java向数据库插入中文出现乱码解决方案

    Java向数据库插入中文出现乱码解决方案

    这篇文章主要介绍了Java向数据库插入中文出现乱码解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Java 如何快速,优雅的实现导出Excel

    Java 如何快速,优雅的实现导出Excel

    这篇文章主要介绍了Java 如何快速,优雅的实现导出Excel,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-03-03
  • Java模拟实现斗地主发牌

    Java模拟实现斗地主发牌

    这篇文章主要为大家详细介绍了Java实现模拟斗地主发牌,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-07-07
  • Springboot整合spring-boot-starter-data-elasticsearch的过程

    Springboot整合spring-boot-starter-data-elasticsearch的过程

    本文详细介绍了Springboot整合spring-boot-starter-data-elasticsearch的过程,包括版本要求、依赖添加、实体类添加、索引的名称、分片、副本设置等,同时,还介绍了如何使用ElasticsearchRepository类进行增删改查操作
    2024-10-10
  • Spring Boot使用Spring的异步线程池的实现

    Spring Boot使用Spring的异步线程池的实现

    这篇文章主要介绍了Spring Boot使用Spring的异步线程池的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-02-02

最新评论