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

Java使用NIO包實(shí)現(xiàn)Socket通信的實(shí)例代碼

 更新時間:2017年02月06日 17:16:40   作者:kongxx  
本篇文章主要介紹了Java使用NIO包實(shí)現(xiàn)Socket通信的實(shí)例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

前面幾篇文章介紹了使用java.io和java.net類庫實(shí)現(xiàn)的Socket通信,下面介紹一下使用java.nio類庫實(shí)現(xiàn)的Socket。

java.nio包是Java在1.4之后增加的,用來提高I/O操作的效率。在nio包中主要包括以下幾個類或接口:

  •  Buffer:緩沖區(qū),用來臨時存放輸入或輸出數(shù)據(jù)。
  •  Charset:用來把Unicode字符編碼和其它字符編碼互轉(zhuǎn)。
  •  Channel:數(shù)據(jù)傳輸通道,用來把Buffer中的數(shù)據(jù)寫入到數(shù)據(jù)源,或者把數(shù)據(jù)源中的數(shù)據(jù)讀入到Buffer。
  •  Selector:用來支持異步I/O操作,也叫非阻塞I/O操作。

nio包中主要通過下面兩個方面來提高I/O操作效率:

  •  通過Buffer和Channel來提高I/O操作的速度。
  •  通過Selector來支持非阻塞I/O操作。

下面來看一下程序中是怎么通過這些類庫實(shí)現(xiàn)Socket功能。

首先介紹一下幾個輔助類

輔助類SerializableUtil,這個類用來把java對象序列化成字節(jié)數(shù)組,或者把字節(jié)數(shù)組反序列化成java對象。

package com.googlecode.garbagecan.test.socket; 
 
import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
 
public class SerializableUtil { 
   
  public static byte[] toBytes(Object object) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ObjectOutputStream oos = null; 
    try { 
      oos = new ObjectOutputStream(baos); 
      oos.writeObject(object); 
      byte[] bytes = baos.toByteArray(); 
      return bytes; 
    } catch(IOException ex) { 
      throw new RuntimeException(ex.getMessage(), ex); 
    } finally { 
      try { 
        oos.close(); 
      } catch (Exception e) {} 
    } 
  } 
   
  public static Object toObject(byte[] bytes) { 
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 
    ObjectInputStream ois = null; 
    try { 
      ois = new ObjectInputStream(bais); 
      Object object = ois.readObject(); 
      return object; 
    } catch(IOException ex) { 
      throw new RuntimeException(ex.getMessage(), ex); 
    } catch(ClassNotFoundException ex) { 
      throw new RuntimeException(ex.getMessage(), ex); 
    } finally { 
      try { 
        ois.close(); 
      } catch (Exception e) {} 
    } 
  } 
} 

輔助類MyRequestObject和MyResponseObject,這兩個類是普通的java對象,實(shí)現(xiàn)了Serializable接口。MyRequestObject類是Client發(fā)出的請求,MyResponseObject是Server端作出的響應(yīng)。

package com.googlecode.garbagecan.test.socket.nio; 
 
import java.io.Serializable; 
 
public class MyRequestObject implements Serializable { 
 
  private static final long serialVersionUID = 1L; 
 
  private String name; 
   
  private String value; 
 
  private byte[] bytes; 
   
  public MyRequestObject(String name, String value) { 
    this.name = name; 
    this.value = value; 
    this.bytes = new byte[1024]; 
  } 
   
  public String getName() { 
    return name; 
  } 
 
  public void setName(String name) { 
    this.name = name; 
  } 
 
  public String getValue() { 
    return value; 
  } 
 
  public void setValue(String value) { 
    this.value = value; 
  } 
   
  @Override 
  public String toString() { 
    StringBuffer sb = new StringBuffer(); 
    sb.append("Request [name: " + name + ", value: " + value + ", bytes: " + bytes.length+ "]"); 
    return sb.toString(); 
  } 
} 
 
package com.googlecode.garbagecan.test.socket.nio; 
 
import java.io.Serializable; 
 
public class MyResponseObject implements Serializable { 
 
  private static final long serialVersionUID = 1L; 
 
  private String name; 
   
  private String value; 
 
  private byte[] bytes; 
   
  public MyResponseObject(String name, String value) { 
    this.name = name; 
    this.value = value; 
    this.bytes = new byte[1024]; 
  } 
   
  public String getName() { 
    return name; 
  } 
 
  public void setName(String name) { 
    this.name = name; 
  } 
 
  public String getValue() { 
    return value; 
  } 
 
  public void setValue(String value) { 
    this.value = value; 
  } 
   
  @Override 
  public String toString() { 
    StringBuffer sb = new StringBuffer(); 
    sb.append("Response [name: " + name + ", value: " + value + ", bytes: " + bytes.length+ "]"); 
    return sb.toString(); 
  } 
} 

下面主要看一下Server端的代碼,其中有一些英文注釋對理解代碼很有幫助,注釋主要是來源jdk的文檔和例子,這里就沒有再翻譯

package com.googlecode.garbagecan.test.socket.nio; 
 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.nio.ByteBuffer; 
import java.nio.channels.ClosedChannelException; 
import java.nio.channels.SelectionKey; 
import java.nio.channels.Selector; 
import java.nio.channels.ServerSocketChannel; 
import java.nio.channels.SocketChannel; 
import java.util.Iterator; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
 
import com.googlecode.garbagecan.test.socket.SerializableUtil; 
 
public class MyServer3 { 
 
  private final static Logger logger = Logger.getLogger(MyServer3.class.getName()); 
   
  public static void main(String[] args) { 
    Selector selector = null; 
    ServerSocketChannel serverSocketChannel = null; 
     
    try { 
      // Selector for incoming time requests 
      selector = Selector.open(); 
 
      // Create a new server socket and set to non blocking mode 
      serverSocketChannel = ServerSocketChannel.open(); 
      serverSocketChannel.configureBlocking(false); 
       
      // Bind the server socket to the local host and port 
      serverSocketChannel.socket().setReuseAddress(true); 
      serverSocketChannel.socket().bind(new InetSocketAddress(10000)); 
       
      // Register accepts on the server socket with the selector. This 
      // step tells the selector that the socket wants to be put on the 
      // ready list when accept operations occur, so allowing multiplexed 
      // non-blocking I/O to take place. 
      serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 
   
      // Here's where everything happens. The select method will 
      // return when any operations registered above have occurred, the 
      // thread has been interrupted, etc. 
      while (selector.select() > 0) { 
        // Someone is ready for I/O, get the ready keys 
        Iterator<SelectionKey> it = selector.selectedKeys().iterator(); 
   
        // Walk through the ready keys collection and process date requests. 
        while (it.hasNext()) { 
          SelectionKey readyKey = it.next(); 
          it.remove(); 
           
          // The key indexes into the selector so you 
          // can retrieve the socket that's ready for I/O 
          execute((ServerSocketChannel) readyKey.channel()); 
        } 
      } 
    } catch (ClosedChannelException ex) { 
      logger.log(Level.SEVERE, null, ex); 
    } catch (IOException ex) { 
      logger.log(Level.SEVERE, null, ex); 
    } finally { 
      try { 
        selector.close(); 
      } catch(Exception ex) {} 
      try { 
        serverSocketChannel.close(); 
      } catch(Exception ex) {} 
    } 
  } 
 
  private static void execute(ServerSocketChannel serverSocketChannel) throws IOException { 
    SocketChannel socketChannel = null; 
    try { 
      socketChannel = serverSocketChannel.accept(); 
      MyRequestObject myRequestObject = receiveData(socketChannel); 
      logger.log(Level.INFO, myRequestObject.toString()); 
       
      MyResponseObject myResponseObject = new MyResponseObject( 
          "response for " + myRequestObject.getName(),  
          "response for " + myRequestObject.getValue()); 
      sendData(socketChannel, myResponseObject); 
      logger.log(Level.INFO, myResponseObject.toString()); 
    } finally { 
      try { 
        socketChannel.close(); 
      } catch(Exception ex) {} 
    } 
  } 
   
  private static MyRequestObject receiveData(SocketChannel socketChannel) throws IOException { 
    MyRequestObject myRequestObject = null; 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ByteBuffer buffer = ByteBuffer.allocate(1024); 
     
    try { 
      byte[] bytes; 
      int size = 0; 
      while ((size = socketChannel.read(buffer)) >= 0) { 
        buffer.flip(); 
        bytes = new byte[size]; 
        buffer.get(bytes); 
        baos.write(bytes); 
        buffer.clear(); 
      } 
      bytes = baos.toByteArray(); 
      Object obj = SerializableUtil.toObject(bytes); 
      myRequestObject = (MyRequestObject)obj; 
    } finally { 
      try { 
        baos.close(); 
      } catch(Exception ex) {} 
    } 
    return myRequestObject; 
  } 
 
  private static void sendData(SocketChannel socketChannel, MyResponseObject myResponseObject) throws IOException { 
    byte[] bytes = SerializableUtil.toBytes(myResponseObject); 
    ByteBuffer buffer = ByteBuffer.wrap(bytes); 
    socketChannel.write(buffer); 
  } 
} 

下面是Client的代碼,代碼比較簡單就是啟動了100個線程來訪問Server

package com.googlecode.garbagecan.test.socket.nio; 
 
import java.io.ByteArrayOutputStream; 
import java.io.IOException; 
import java.net.InetSocketAddress; 
import java.net.SocketAddress; 
import java.nio.ByteBuffer; 
import java.nio.channels.SocketChannel; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
 
import com.googlecode.garbagecan.test.socket.SerializableUtil; 
 
public class MyClient3 { 
 
  private final static Logger logger = Logger.getLogger(MyClient3.class.getName()); 
   
  public static void main(String[] args) throws Exception { 
    for (int i = 0; i < 100; i++) { 
      final int idx = i; 
      new Thread(new MyRunnable(idx)).start(); 
    } 
  } 
   
  private static final class MyRunnable implements Runnable { 
     
    private final int idx; 
 
    private MyRunnable(int idx) { 
      this.idx = idx; 
    } 
 
    public void run() { 
      SocketChannel socketChannel = null; 
      try { 
        socketChannel = SocketChannel.open(); 
        SocketAddress socketAddress = new InetSocketAddress("localhost", 10000); 
        socketChannel.connect(socketAddress); 
 
        MyRequestObject myRequestObject = new MyRequestObject("request_" + idx, "request_" + idx); 
        logger.log(Level.INFO, myRequestObject.toString()); 
        sendData(socketChannel, myRequestObject); 
         
        MyResponseObject myResponseObject = receiveData(socketChannel); 
        logger.log(Level.INFO, myResponseObject.toString()); 
      } catch (Exception ex) { 
        logger.log(Level.SEVERE, null, ex); 
      } finally { 
        try { 
          socketChannel.close(); 
        } catch(Exception ex) {} 
      } 
    } 
 
    private void sendData(SocketChannel socketChannel, MyRequestObject myRequestObject) throws IOException { 
      byte[] bytes = SerializableUtil.toBytes(myRequestObject); 
      ByteBuffer buffer = ByteBuffer.wrap(bytes); 
      socketChannel.write(buffer); 
      socketChannel.socket().shutdownOutput(); 
    } 
 
    private MyResponseObject receiveData(SocketChannel socketChannel) throws IOException { 
      MyResponseObject myResponseObject = null; 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
       
      try { 
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024); 
        byte[] bytes; 
        int count = 0; 
        while ((count = socketChannel.read(buffer)) >= 0) { 
          buffer.flip(); 
          bytes = new byte[count]; 
          buffer.get(bytes); 
          baos.write(bytes); 
          buffer.clear(); 
        } 
        bytes = baos.toByteArray(); 
        Object obj = SerializableUtil.toObject(bytes); 
        myResponseObject = (MyResponseObject) obj; 
        socketChannel.socket().shutdownInput(); 
      } finally { 
        try { 
          baos.close(); 
        } catch(Exception ex) {} 
      } 
      return myResponseObject; 
    } 
  } 
} 

最后測試上面的代碼,首先運(yùn)行Server類,然后運(yùn)行Client類,就可以分別在Server端和Client端控制臺看到發(fā)送或接收到的MyRequestObject或MyResponseObject對象了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • XML操作類庫XStream使用詳解

    XML操作類庫XStream使用詳解

    這篇文章主要給大家介紹了關(guān)于XML操作類庫XStream使用的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • spring框架cacheAnnotation緩存注釋聲明解析

    spring框架cacheAnnotation緩存注釋聲明解析

    這篇文章主要介紹了spring框架中cacheAnnotation注釋聲明緩存解析示例有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-10-10
  • 使用springboot打包成zip部署,并實(shí)現(xiàn)優(yōu)雅停機(jī)

    使用springboot打包成zip部署,并實(shí)現(xiàn)優(yōu)雅停機(jī)

    這篇文章主要介紹了使用springboot打包成zip部署,并實(shí)現(xiàn)優(yōu)雅停機(jī),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 一文帶你深入了解Java泛型

    一文帶你深入了解Java泛型

    Java?泛型(generics)是?Jdk?5?中引入的一個新特性,?泛型提供了編譯時類型安全檢測機(jī)制,?該機(jī)制允許程序員在編譯時檢測到非法的類型。本文將通過示例詳解Java泛型的定義與使用,需要的可以參考一下
    2022-08-08
  • Spring整合Mybatis思路梳理總結(jié)

    Spring整合Mybatis思路梳理總結(jié)

    mybatis-plus是一個 Mybatis 的增強(qiáng)工具,在 Mybatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡化開發(fā)、提高效率而生,下面這篇文章主要給大家介紹了關(guān)于SpringBoot整合Mybatis-plus案例及用法實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2022-12-12
  • 淺談idea live template高級知識_進(jìn)階(給方法,類,js方法添加注釋)

    淺談idea live template高級知識_進(jìn)階(給方法,類,js方法添加注釋)

    下面小編就為大家?guī)硪黄獪\談idea live template高級知識_進(jìn)階(給方法,類,js方法添加注釋)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 深入理解Java中的注解Annotation

    深入理解Java中的注解Annotation

    這篇文章主要介紹了深入理解Java中的注解Annotation,注解在Java中確實(shí)也很常見,但是人們常常不會自己定義一個注解拿來用,我們雖然很少去自定義注解,但是學(xué)會注解的寫法,注解的定義,學(xué)會利用反射解析注解中的信息,在開發(fā)中能夠使用到,這是很關(guān)鍵的,需要的朋友可以參考下
    2023-10-10
  • Java輕松掌握面向?qū)ο蟮娜筇匦苑庋b與繼承和多態(tài)

    Java輕松掌握面向?qū)ο蟮娜筇匦苑庋b與繼承和多態(tài)

    本文主要講述的是面向?qū)ο蟮娜筇匦裕悍庋b,繼承,多態(tài),內(nèi)容含括從封裝到繼承再到多態(tài)的所有重點(diǎn)內(nèi)容以及使用細(xì)節(jié)和注意事項,內(nèi)容有點(diǎn)長,請大家耐心看完
    2022-05-05
  • Springboot項目打包如何將依賴的jar包輸出到指定目錄

    Springboot項目打包如何將依賴的jar包輸出到指定目錄

    公司要對springboot項目依賴的jar包進(jìn)行升級,但是遇到一個問題,項目打包之后,沒辦法看到他里面依賴的jar包,版本到底是不是升上去了,沒辦法看到,下面通過本文給大家分享Springboot項目打包如何將依賴的jar包輸出到指定目錄,感興趣的朋友一起看看吧
    2024-05-05
  • Java流程控制語句最全匯總(中篇)

    Java流程控制語句最全匯總(中篇)

    這篇文章主要介紹了Java流程控制語句最全匯總(中篇),本文章內(nèi)容詳細(xì),通過案例可以更好的理解數(shù)組的相關(guān)知識,本模塊分為了三部分,本次為中篇,需要的朋友可以參考下
    2023-01-01

最新評論

邯郸县| 祁连县| 大埔区| 治多县| 绩溪县| 卢湾区| 呼玛县| 汾阳市| 班玛县| 清新县| 罗甸县| 裕民县| 阿坝县| 南康市| 霞浦县| 青铜峡市| 泽普县| 阳山县| 乌兰浩特市| 宜兰市| 深水埗区| 长沙县| 安康市| 井研县| 南雄市| 蒙阴县| 金乡县| 上高县| 色达县| 西丰县| 扶沟县| 榆中县| 绥中县| 商水县| 永年县| 栾川县| 定结县| 丽江市| 招远市| 万州区| 福贡县|