最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java Socket編程實(shí)例(四)- NIO TCP實(shí)踐

 更新時(shí)間:2016年06月15日 09:52:59   作者:kingxss  
這篇文章主要講解Java Socket編程中NIO TCP的實(shí)例,希望能給大家做一個(gè)參考。

一、回傳協(xié)議接口和TCP方式實(shí)現(xiàn):

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.實(shí)現(xiàn):

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服務(wù)端:

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

以上就是本文的全部?jī)?nèi)容,查看更多Java的語(yǔ)法,大家可以關(guān)注:《Thinking in Java 中文手冊(cè)》、《JDK 1.7 參考手冊(cè)官方英文版》、《JDK 1.6 API java 中文參考手冊(cè)》、《JDK 1.5 API java 中文參考手冊(cè)》,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java使用DualPivotQuicksort排序

    Java使用DualPivotQuicksort排序

    這篇文章主要介紹了Java使用DualPivotQuicksort排序,喜歡算法的同學(xué)一定要看一下
    2021-04-04
  • SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟

    SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟

    這篇文章主要介紹了SpringBoot+Redis執(zhí)行l(wèi)ua腳本的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Springboot中Instant時(shí)間傳參及序列化詳解

    Springboot中Instant時(shí)間傳參及序列化詳解

    這篇文章主要介紹了Springboot中Instant時(shí)間傳參及序列化詳解,Instant是Java8引入的一個(gè)精度極高的時(shí)間類型,可以精確到納秒,但實(shí)際使用的時(shí)候不需要這么高的精確度,通常到毫秒就可以了,需要的朋友可以參考下
    2023-11-11
  • 基于springboot2集成jpa,創(chuàng)建dao的案例

    基于springboot2集成jpa,創(chuàng)建dao的案例

    這篇文章主要介紹了基于springboot2集成jpa,創(chuàng)建dao的案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2021-01-01
  • springboot接收日期類型參數(shù)的操作方法

    springboot接收日期類型參數(shù)的操作方法

    如果使用Get請(qǐng)求,直接使用對(duì)象接收,則可以使用@DateTimeFormat注解進(jìn)行格式化,本文重點(diǎn)給大家介紹springboot接收日期類型參數(shù)的方法,感興趣的朋友一起看看吧
    2024-02-02
  • Java向數(shù)據(jù)庫(kù)插入中文出現(xiàn)亂碼解決方案

    Java向數(shù)據(jù)庫(kù)插入中文出現(xiàn)亂碼解決方案

    這篇文章主要介紹了Java向數(shù)據(jù)庫(kù)插入中文出現(xiàn)亂碼解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Java 如何快速,優(yōu)雅的實(shí)現(xiàn)導(dǎo)出Excel

    Java 如何快速,優(yōu)雅的實(shí)現(xiàn)導(dǎo)出Excel

    這篇文章主要介紹了Java 如何快速,優(yōu)雅的實(shí)現(xiàn)導(dǎo)出Excel,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下
    2021-03-03
  • Java模擬實(shí)現(xiàn)斗地主發(fā)牌

    Java模擬實(shí)現(xiàn)斗地主發(fā)牌

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)模擬斗地主發(fā)牌,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Springboot整合spring-boot-starter-data-elasticsearch的過程

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

    本文詳細(xì)介紹了Springboot整合spring-boot-starter-data-elasticsearch的過程,包括版本要求、依賴添加、實(shí)體類添加、索引的名稱、分片、副本設(shè)置等,同時(shí),還介紹了如何使用ElasticsearchRepository類進(jìn)行增刪改查操作
    2024-10-10
  • Spring Boot使用Spring的異步線程池的實(shí)現(xiàn)

    Spring Boot使用Spring的異步線程池的實(shí)現(xiàn)

    這篇文章主要介紹了Spring Boot使用Spring的異步線程池的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02

最新評(píng)論

乐平市| 正阳县| 铁岭市| 嘉兴市| 三亚市| 桐柏县| 山东| 乐业县| 含山县| 上饶县| 博爱县| 万载县| 普格县| 手游| 诏安县| 长阳| 赣榆县| 西平县| 当雄县| 疏勒县| 闻喜县| 五常市| 黑山县| 富裕县| 镇坪县| 焉耆| 赫章县| 顺平县| 博湖县| 卓尼县| 新和县| 易门县| 桃江县| 偏关县| 渝中区| 登封市| 泰宁县| 阜宁县| 西平县| 奇台县| 潞城市|