Java Socket Combat six uses the NIO package to implement the socket communication

Source: Internet
Author: User
Tags getmessage int size object object stringbuffer

This article address: http://blog.csdn.net/kongxx/article/details/7288896

Java socket Combat one single-threaded communication

Java Socket combat two multi-thread communication

Java socket Three-combat Transfer object

Java socket in combat four transmission compressed objects

Java Socket actual combat five uses the encryption protocol to transfer objects

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.

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 Bytear
		Rayoutputstream ();
		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 Bytearr
		Ayinputstream (bytes);
		ObjectInputStream ois = null;
			try {ois = new ObjectInputStream (Bais);
			Object object = Ois.readobject ();
		return object; The catch (IOException ex) {throw new RuntimeException (Ex.getmessage),ex);
		catch (ClassNotFoundException ex) {throw new RuntimeException (Ex.getmessage (), ex);
			Finally {try {ois.close (); The catch (Exception e) {}}}}
Auxiliary classes Myrequestobject and Myresponseobject, these two classes are ordinary Java objects that implement the Serializable interface. The Myrequestobject class is a client-issued request, and Myresponseobject is a response from the server side.

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 (); }
}

Here's a look at the server-side code, some of which are helpful for understanding the code, mainly the documentation and examples of the source JDK, no more translations

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, the socket wants to is put on the//Ready list When accept operations occur, s
			o allowing multiplexed//non-blocking I/O to take place.
	
			Serversocketchannel.register (selector, selectionkey.op_accept); Here ' s where everything happens. The Select method would//return as any operations registered above have occurred, the//thread has been
			Ted, etc.  while (Selector.select () > 0) {//Someone are 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"/can retrieve the socket that "s ready for I/O Execute (Serversocke
				TChannel) Readykey.channel ());
		The catch (Closedchannelexception ex) {logger.log (level.severe, NULL, ex);
		catch (IOException ex) {logger.log (level.severe, NULL, ex);
			Finally {try {selector.close ();
			The 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 (), "respons
			E 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 Ioexcept
		Ion {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 ();
	The catch (Exception ex) {}} return myrequestobject; private static void SendData (Socketchannel socketchannel, Myresponseobject myresponseobject) throws IOException {by te[] bytes = Serializableutil. Tobytes (Myresponseobject);
		Bytebuffer buffer = bytebuffer.wrap (bytes);
	Socketchannel.write (buffer); }
}
The following is the client code, which is simpler to start with 100 threads to access the 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 < 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) t
			Hrows 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 MyResponse
			Object = 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 ();
		The catch (Exception ex) {}} return myresponseobject;
 }
	}
}

Finally, test the code above, run the server class first, and then run the client class to see the Myrequestobject or Myresponseobject objects that were sent or received, respectively, on the server side and the client side console.

For a comparison of NiO and Io, the following two articles are helpful for understanding, and can be consulted.

Http://tutorials.jenkov.com/java-nio/nio-vs-io.html

Https://blogs.oracle.com/slc/entry/javanio_vs_javaio


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.