本文地址:http://blog.csdn.net/kongxx/article/details/7288896
Java Socket實戰之一 單線程通訊
Java Socket實戰之二 多線程通訊
Java Socket實戰之三 傳輸對象
Java Socket實戰之四 傳輸壓縮對象
Java Socket實戰之五 使用加密協議傳輸對象
前面幾篇文章介紹了使用java.io和java.net類庫實現的Socket通訊,下面介紹一下使用java.nio類庫實現的Socket。
java.nio包是Java在1.4之後增加的,用來提高I/O操作的效率。在nio包中主要包括以下幾個類或介面:
* Buffer:緩衝區,用來臨時存放輸入或輸出資料。
* Charset:用來把Unicode字元編碼和其它字元編碼互轉。
* Channel:資料轉送通道,用來把Buffer中的資料寫入到資料來源,或者把資料來源中的資料讀入到Buffer。
* Selector:用來支援非同步I/O操作,也叫非阻塞I/O操作。
nio包中主要通過下面兩個方面來提高I/O操作效率:
* 通過Buffer和Channel來提高I/O操作的速度。
* 通過Selector來支援非阻塞I/O操作。
下面來看一下程式中是怎麼通過這些類庫實現Socket功能。
首先介紹一下幾個輔助類
輔助類SerializableUtil,這個類用來把java對象序列化成位元組數組,或者把位元組數組還原序列化成java對象。
package com.googlecode.garbagecan.test.socket;</p><p>import java.io.ByteArrayInputStream;<br />import java.io.ByteArrayOutputStream;<br />import java.io.IOException;<br />import java.io.ObjectInputStream;<br />import java.io.ObjectOutputStream;</p><p>public class SerializableUtil {</p><p>public static byte[] toBytes(Object object) {<br />ByteArrayOutputStream baos = new ByteArrayOutputStream();<br />ObjectOutputStream oos = null;<br />try {<br />oos = new ObjectOutputStream(baos);<br />oos.writeObject(object);<br />byte[] bytes = baos.toByteArray();<br />return bytes;<br />} catch(IOException ex) {<br />throw new RuntimeException(ex.getMessage(), ex);<br />} finally {<br />try {<br />oos.close();<br />} catch (Exception e) {}<br />}<br />}</p><p>public static Object toObject(byte[] bytes) {<br />ByteArrayInputStream bais = new ByteArrayInputStream(bytes);<br />ObjectInputStream ois = null;<br />try {<br />ois = new ObjectInputStream(bais);<br />Object object = ois.readObject();<br />return object;<br />} catch(IOException ex) {<br />throw new RuntimeException(ex.getMessage(), ex);<br />} catch(ClassNotFoundException ex) {<br />throw new RuntimeException(ex.getMessage(), ex);<br />} finally {<br />try {<br />ois.close();<br />} catch (Exception e) {}<br />}<br />}<br />}輔助類MyRequestObject和MyResponseObject,這兩個類是普通的java對象,實現了Serializable介面。MyRequestObject類是Client發出的請求,MyResponseObject是Server端作出的響應。
package com.googlecode.garbagecan.test.socket.nio;</p><p>import java.io.Serializable;</p><p>public class MyRequestObject implements Serializable {</p><p>private static final long serialVersionUID = 1L;</p><p>private String name;</p><p>private String value;</p><p>private byte[] bytes;</p><p>public MyRequestObject(String name, String value) {<br />this.name = name;<br />this.value = value;<br />this.bytes = new byte[1024];<br />}</p><p>public String getName() {<br />return name;<br />}</p><p>public void setName(String name) {<br />this.name = name;<br />}</p><p>public String getValue() {<br />return value;<br />}</p><p>public void setValue(String value) {<br />this.value = value;<br />}</p><p>@Override<br />public String toString() {<br />StringBuffer sb = new StringBuffer();<br />sb.append("Request [name: " + name + ", value: " + value + ", bytes: " + bytes.length+ "]");<br />return sb.toString();<br />}<br />}</p><p>package com.googlecode.garbagecan.test.socket.nio;</p><p>import java.io.Serializable;</p><p>public class MyResponseObject implements Serializable {</p><p>private static final long serialVersionUID = 1L;</p><p>private String name;</p><p>private String value;</p><p>private byte[] bytes;</p><p>public MyResponseObject(String name, String value) {<br />this.name = name;<br />this.value = value;<br />this.bytes = new byte[1024];<br />}</p><p>public String getName() {<br />return name;<br />}</p><p>public void setName(String name) {<br />this.name = name;<br />}</p><p>public String getValue() {<br />return value;<br />}</p><p>public void setValue(String value) {<br />this.value = value;<br />}</p><p>@Override<br />public String toString() {<br />StringBuffer sb = new StringBuffer();<br />sb.append("Response [name: " + name + ", value: " + value + ", bytes: " + bytes.length+ "]");<br />return sb.toString();<br />}<br />}
下面主要看一下Server端的代碼,其中有一些英文注釋對理解代碼很有協助,注釋主要是來源jdk的文檔和例子,這裡就沒有再翻譯
package com.googlecode.garbagecan.test.socket.nio;</p><p>import java.io.ByteArrayOutputStream;<br />import java.io.IOException;<br />import java.net.InetSocketAddress;<br />import java.nio.ByteBuffer;<br />import java.nio.channels.ClosedChannelException;<br />import java.nio.channels.SelectionKey;<br />import java.nio.channels.Selector;<br />import java.nio.channels.ServerSocketChannel;<br />import java.nio.channels.SocketChannel;<br />import java.util.Iterator;<br />import java.util.logging.Level;<br />import java.util.logging.Logger;</p><p>import com.googlecode.garbagecan.test.socket.SerializableUtil;</p><p>public class MyServer3 {</p><p>private final static Logger logger = Logger.getLogger(MyServer3.class.getName());</p><p>public static void main(String[] args) {<br />Selector selector = null;<br />ServerSocketChannel serverSocketChannel = null;</p><p>try {<br />// Selector for incoming time requests<br />selector = Selector.open();</p><p>// Create a new server socket and set to non blocking mode<br />serverSocketChannel = ServerSocketChannel.open();<br />serverSocketChannel.configureBlocking(false);</p><p>// Bind the server socket to the local host and port<br />serverSocketChannel.socket().setReuseAddress(true);<br />serverSocketChannel.socket().bind(new InetSocketAddress(10000));</p><p>// Register accepts on the server socket with the selector. This<br />// step tells the selector that the socket wants to be put on the<br />// ready list when accept operations occur, so allowing multiplexed<br />// non-blocking I/O to take place.<br />serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);</p><p>// Here's where everything happens. The select method will<br />// return when any operations registered above have occurred, the<br />// thread has been interrupted, etc.<br />while (selector.select() > 0) {<br />// Someone is ready for I/O, get the ready keys<br />Iterator<SelectionKey> it = selector.selectedKeys().iterator();</p><p>// Walk through the ready keys collection and process date requests.<br />while (it.hasNext()) {<br />SelectionKey readyKey = it.next();<br />it.remove();</p><p>// The key indexes into the selector so you<br />// can retrieve the socket that's ready for I/O<br />execute((ServerSocketChannel) readyKey.channel());<br />}<br />}<br />} catch (ClosedChannelException ex) {<br />logger.log(Level.SEVERE, null, ex);<br />} catch (IOException ex) {<br />logger.log(Level.SEVERE, null, ex);<br />} finally {<br />try {<br />selector.close();<br />} catch(Exception ex) {}<br />try {<br />serverSocketChannel.close();<br />} catch(Exception ex) {}<br />}<br />}</p><p>private static void execute(ServerSocketChannel serverSocketChannel) throws IOException {<br />SocketChannel socketChannel = null;<br />try {<br />socketChannel = serverSocketChannel.accept();<br />MyRequestObject myRequestObject = receiveData(socketChannel);<br />logger.log(Level.INFO, myRequestObject.toString());</p><p>MyResponseObject myResponseObject = new MyResponseObject(<br />"response for " + myRequestObject.getName(),<br />"response for " + myRequestObject.getValue());<br />sendData(socketChannel, myResponseObject);<br />logger.log(Level.INFO, myResponseObject.toString());<br />} finally {<br />try {<br />socketChannel.close();<br />} catch(Exception ex) {}<br />}<br />}</p><p>private static MyRequestObject receiveData(SocketChannel socketChannel) throws IOException {<br />MyRequestObject myRequestObject = null;<br />ByteArrayOutputStream baos = new ByteArrayOutputStream();<br />ByteBuffer buffer = ByteBuffer.allocate(1024);</p><p>try {<br />byte[] bytes;<br />int size = 0;<br />while ((size = socketChannel.read(buffer)) >= 0) {<br />buffer.flip();<br />bytes = new byte[size];<br />buffer.get(bytes);<br />baos.write(bytes);<br />buffer.clear();<br />}<br />bytes = baos.toByteArray();<br />Object obj = SerializableUtil.toObject(bytes);<br />myRequestObject = (MyRequestObject)obj;<br />} finally {<br />try {<br />baos.close();<br />} catch(Exception ex) {}<br />}<br />return myRequestObject;<br />}</p><p>private static void sendData(SocketChannel socketChannel, MyResponseObject myResponseObject) throws IOException {<br />byte[] bytes = SerializableUtil.toBytes(myResponseObject);<br />ByteBuffer buffer = ByteBuffer.wrap(bytes);<br />socketChannel.write(buffer);<br />}<br />}下面是Client的代碼,代碼比較簡單就是啟動了100個線程來訪問Server
package com.googlecode.garbagecan.test.socket.nio;</p><p>import java.io.ByteArrayOutputStream;<br />import java.io.IOException;<br />import java.net.InetSocketAddress;<br />import java.net.SocketAddress;<br />import java.nio.ByteBuffer;<br />import java.nio.channels.SocketChannel;<br />import java.util.logging.Level;<br />import java.util.logging.Logger;</p><p>import com.googlecode.garbagecan.test.socket.SerializableUtil;</p><p>public class MyClient3 {</p><p>private final static Logger logger = Logger.getLogger(MyClient3.class.getName());</p><p>public static void main(String[] args) throws Exception {<br />for (int i = 0; i < 100; i++) {<br />final int idx = i;<br />new Thread(new MyRunnable(idx)).start();<br />}<br />}</p><p>private static final class MyRunnable implements Runnable {</p><p>private final int idx;</p><p>private MyRunnable(int idx) {<br />this.idx = idx;<br />}</p><p>public void run() {<br />SocketChannel socketChannel = null;<br />try {<br />socketChannel = SocketChannel.open();<br />SocketAddress socketAddress = new InetSocketAddress("localhost", 10000);<br />socketChannel.connect(socketAddress);</p><p>MyRequestObject myRequestObject = new MyRequestObject("request_" + idx, "request_" + idx);<br />logger.log(Level.INFO, myRequestObject.toString());<br />sendData(socketChannel, myRequestObject);</p><p>MyResponseObject myResponseObject = receiveData(socketChannel);<br />logger.log(Level.INFO, myResponseObject.toString());<br />} catch (Exception ex) {<br />logger.log(Level.SEVERE, null, ex);<br />} finally {<br />try {<br />socketChannel.close();<br />} catch(Exception ex) {}<br />}<br />}</p><p>private void sendData(SocketChannel socketChannel, MyRequestObject myRequestObject) throws IOException {<br />byte[] bytes = SerializableUtil.toBytes(myRequestObject);<br />ByteBuffer buffer = ByteBuffer.wrap(bytes);<br />socketChannel.write(buffer);<br />socketChannel.socket().shutdownOutput();<br />}</p><p>private MyResponseObject receiveData(SocketChannel socketChannel) throws IOException {<br />MyResponseObject myResponseObject = null;<br />ByteArrayOutputStream baos = new ByteArrayOutputStream();</p><p>try {<br />ByteBuffer buffer = ByteBuffer.allocateDirect(1024);<br />byte[] bytes;<br />int count = 0;<br />while ((count = socketChannel.read(buffer)) >= 0) {<br />buffer.flip();<br />bytes = new byte[count];<br />buffer.get(bytes);<br />baos.write(bytes);<br />buffer.clear();<br />}<br />bytes = baos.toByteArray();<br />Object obj = SerializableUtil.toObject(bytes);<br />myResponseObject = (MyResponseObject) obj;<br />socketChannel.socket().shutdownInput();<br />} finally {<br />try {<br />baos.close();<br />} catch(Exception ex) {}<br />}<br />return myResponseObject;<br />}<br />}<br />}<br />
最後測試上面的代碼,首先運行Server類,然後運行Client類,就可以分別在Server端和Client端控制台看到發送或接收到的MyRequestObject或MyResponseObject對象了。
關於NIO和IO的比較,下面的兩篇文章對理解很有協助,可以參考一下。
http://tutorials.jenkov.com/java-nio/nio-vs-io.html
https://blogs.oracle.com/slc/entry/javanio_vs_javaio