欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

一、回傳協(xié)議接口和TCP方式實現(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.實現(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 
      } 
    } 
  } 
   
} 

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

相關(guān)文章

  • 詳解Java中-classpath和路徑的使用

    詳解Java中-classpath和路徑的使用

    本篇文章主要介紹了Java中-classpath和路徑的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • SpringBoot讀取yaml文件操作詳解

    SpringBoot讀取yaml文件操作詳解

    YAML 是 “YAML Ain’t Markup Language”(YAML 不是一種標(biāo)記語言)的遞歸縮寫。在開發(fā)的這種語言時,YAML 的意思其實是:“Yet Another Markup Language”(仍是一種標(biāo)記語言),本文給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09
  • Spring的編程式事務(wù)TransactionTemplate的用法詳解

    Spring的編程式事務(wù)TransactionTemplate的用法詳解

    TransactionTemplate提供了一種在代碼中進(jìn)行編程式事務(wù)管理的方式,使開發(fā)人員能夠在方法級別定義事務(wù)的開始和結(jié)束點,本文介紹了Spring框架中TransactionTemplate的用法,感興趣的朋友跟隨小編一起看看吧
    2023-07-07
  • Java中實現(xiàn)漢字生成拼音首拼和五筆碼

    Java中實現(xiàn)漢字生成拼音首拼和五筆碼

    這篇文章主要介紹了Java中實現(xiàn)漢字生成拼音首拼和五筆碼方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 詳解使用spring validation完成數(shù)據(jù)后端校驗

    詳解使用spring validation完成數(shù)據(jù)后端校驗

    這篇文章主要介紹了詳解使用spring validation完成數(shù)據(jù)后端校驗,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • 為何修改equals方法時還要重寫hashcode方法的原因分析

    為何修改equals方法時還要重寫hashcode方法的原因分析

    這篇文章主要介紹了為何修改equals方法時還要重寫hashcode方法的原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 淺談JAVA在項目中如何自定義異常

    淺談JAVA在項目中如何自定義異常

    今天給大家?guī)淼氖顷P(guān)于Java的相關(guān)知識,文章圍繞著JAVA在項目中如何自定義異常展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • 基于mybatis進(jìn)行批量更新兩種方法

    基于mybatis進(jìn)行批量更新兩種方法

    這篇文章主要給大家介紹了關(guān)于如何基于mybatis進(jìn)行批量更新的兩種方法,批量更新的使用,mybatis中批量更新有很多種方法,可以把數(shù)據(jù)一條條更新,也可以傳入一個數(shù)據(jù)集一次性更新,需要的朋友可以參考下
    2023-08-08
  • Spring Boot自定義配置實現(xiàn)IDE自動提示功能

    Spring Boot自定義配置實現(xiàn)IDE自動提示功能

    這篇文章主要介紹了Spring Boot自定義配置實現(xiàn)IDE自動提示功能,本文圖文并茂給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • 詳解Java如何利用數(shù)字描述更多的信息

    詳解Java如何利用數(shù)字描述更多的信息

    在數(shù)據(jù)庫里面?,通常我們會用數(shù)字的遞進(jìn)來描述狀態(tài)等信息?,?但是如果想進(jìn)行更復(fù)雜的操作?,?就有必要對二進(jìn)制有一定理解了。本文就來趣味性的探討一下?,?如何通過更少的空間描述更多的信息
    2022-09-09

最新評論