This article address: http://blog.csdn.net/kongxx/article/details/7288896
The previous articles introduced socket communication using the Java.io and Java.net class libraries, and the following are some of the sockets that are implemented using the Java.nio class library.
The Java.nio package is added to Java after 1.4 to increase the efficiency of I/O operations. The following classes or interfaces are mainly included in the NIO package:
* Buffer: Buffers for temporary storage of input or output data.
* Charset: Used to turn Unicode character encoding and other character encoding to each other.
* Channel: Data transmission channel, which is used to write information in the buffer to the data source, or to read the data from the data source into the buffer.
* Selector: Used to support asynchronous I/O operations, also known as non-blocking I/O operations.
The following two areas are the main ways to improve I/O efficiency in the NIO package:
* Increase the speed of I/O operations through buffer and channel.
* Selector to support non-blocking I/O operations.
Let's take a look at how the program implements the socket function through these class libraries.
First, introduce a few auxiliary classes
Helper class Serializableutil, which is used to serialize Java objects into byte arrays, or to deserialize byte arrays into Java objects.
[Java] View plain copy print? 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; &nbSp; } 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) {} } }