Practice of Client/server program based on NIO

Source: Internet
Author: User
Tags serialization

The idea is to see how the code inside the zookeeper is playing, after pondering over a period of time, and found himself to write an independent of NIO based on the C/S model program, to see what the nuances to pay attention to, and then follow ZK's details more reliable, and then on their own handwriting the following code, Power when the use of NIO to write a network program of the knowledge Point, here, the purpose of writing this code is to deepen their own impression, and follow-up can also have to think and improve the space.

Basic function: Server end to send "How are to client", the client keeps receiving the message, receives the message then sends the greeting to the server side "Server,how Are you?"

(1) server-side programs

Package Com.hadoop.nio;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
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.Set;

	/** * @author Administrator */public class Niosocketserver extends Thread {private Selector Selector;

	Private Serversocketchannel SSC;
		/** * @param args */public static void main (string[] args) {niosocketserver server = new Niosocketserver ();
			try {//Server.setdaemon (TRUE);
			Server.initserver ();
		Server.start ();
			catch (Exception e) {e.printstacktrace ();
		Server.stopserver ();
				} public void Run () {while (true) {try {int select = Selector.select (); if (select > 0) {set<selectionkey> keys = SelectoR.selectedkeys ();
					Iterator<selectionkey> iter = Keys.iterator ();
						while (Iter.hasnext ()) {Selectionkey key = Iter.next ();
						if (key.isacceptable ()) {doacceptable (key);
						} if (Key.iswritable ()) {dowritemessage (key);
						} if (Key.isreadable ()) {doreadmessage (key);
						} if (Key.isconnectable ()) {doconnectable (key);
					} iter.remove ();
			A catch (Exception e) {e.printstacktrace ()); /** * Initialize server-side program, start listening port * * @throws IOException * @throws closedchannelexception * * private void INI

		Tserver () throws IOException, closedchannelexception {selector = Selector.open ();
		SSC = Serversocketchannel.open ();
		Ssc.configureblocking (FALSE);
		Ssc.socket (). bind (New Inetsocketaddress (2181));
	Ssc.register (selector, selectionkey.op_accept); /** * Stop Server side */private void Stopserver () {try {if (selector!= null && selector.isopen ()) {s EleCtor.close ();
			} if (SSC!= null && ssc.isopen ()) {ssc.close ());
		} catch (IOException e) {e.printstacktrace (); /** * Handles new client connections * @param key * @throws IOException * @throws closedchannelexception * * Private V
		OID doacceptable (Selectionkey key) throws IOException, closedchannelexception {System.out.println ("is acceptable");
		Serversocketchannel TEMPSSC = (serversocketchannel) key.channel ();
		Socketchannel ss = Tempssc.accept ();
		Ss.configureblocking (FALSE); Ss.register (Selector, Selectionkey.op_read |
	Selectionkey.op_write); /** * Write message to Client * * @param key * @throws IOException * @throws unsupportedencodingexception/Private Voi D dowritemessage (Selectionkey key) throws IOException, unsupportedencodingexception {System.out.println ("is writable
		");
		Socketchannel sc = (socketchannel) key.channel (); Bytebuffer buffer = Bytebuffer.wrap ("How are You?").
		GetBytes ("UTF-8")); while (Buffer.hasremaining ()) {sc.write (buffer);
	}//Sk.interestops (Selectionkey.op_read); /** * Read the message passed by the client * * @param key * @throws IOException * @throws unsupportedencodingexception * * privat e void Doreadmessage (Selectionkey key) throws IOException, unsupportedencodingexception {System.out.println ("is read
		Able ");

		Socketchannel sc = (socketchannel) key.channel ();
		Bytebuffer BB = bytebuffer.allocate (8);
		System.out.println ("Receive from Clint:");
		int read = Sc.read (BB);

			while (Read > 0) {bb.flip ();
			Byte[] Barr = new Byte[bb.limit ()];

			Bb.get (Barr);
			System.out.print (New String (Barr, "UTF-8"));

			Bb.clear ();
		Read = Sc.read (BB);
		} System.out.println ("");
	Sk.interestops (Selectionkey.op_write); /** * Connected * * @param key/private void doconnectable (Selectionkey key) {System.out.println ("is connecta
	Lbe "); } (2) client program
/** * * * * * * Package Com.hadoop.nio;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
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.SocketChannel;
Import Java.util.Iterator;

Import Java.util.Set;
	/** * @author Administrator */public class Niosocketclient extends Thread {private Socketchannel socketchannel;

	Private Selector Selector;
		/** * @param args */public static void main (string[] args) {niosocketclient client = new Niosocketclient ();
			try {client.initclient ();
			Client.start ();
		Client.setdaemon (TRUE);
			catch (Exception e) {e.printstacktrace ();
		Client.stopserver ();

				} public void Run () {while (true) {try {//write message to server-side writemessage ();
				int select = Selector.select (); if (select > 0) {set<selectionkey> keys = SELector.selectedkeys ();
					Iterator<selectionkey> iter = Keys.iterator ();
						while (Iter.hasnext ()) {Selectionkey SK = Iter.next ();
						if (sk.isreadable ()) {readmessage (SK);
					} iter.remove ();
			A catch (Exception e) {e.printstacktrace ()); }} public void Readmessage (Selectionkey sk) throws IOException, unsupportedencodingexception {Socketchannel
		CURSC = (Socketchannel) sk.channel ();
		Bytebuffer buffer = bytebuffer.allocate (8);
			while (cursc.read (buffer) > 0) {buffer.flip ();
			System.out.println ("Receive from server:" + New String (Buffer.array (), "UTF-8"));
		Buffer.clear ();
			} public void Writemessage () throws IOException {try {String ss = ' server,how are you ';
			Bytebuffer buffer = Bytebuffer.wrap (ss.getbytes ("UTF-8"));
				while (Buffer.hasremaining ()) {System.out.println ("buffer.hasremaining () is true.");
			Socketchannel.write (buffer); } catch (IOException e) {if (Socketchannel.isopen ()) {socketchannel.close ();
		} e.printstacktrace (); } public void Initclient () throws IOException, closedchannelexception {inetsocketaddress addr = new Inetsocketaddr
		ESS (2181);

		Socketchannel = Socketchannel.open ();
		selector = Selector.open ();
		Socketchannel.configureblocking (FALSE);

		Socketchannel.register (selector, selectionkey.op_read);

		Connect to the server Socketchannel.connect (addr);
		while (!socketchannel.finishconnect ()) {System.out.println ("Check finish connection");
				}/** * Stop client */private void Stopserver () {try {if (selector!= null && selector.isopen ()) {
			Selector.close ();
			} if (Socketchannel!= null && socketchannel.isopen ()) {socketchannel.close ();
		} catch (IOException e) {e.printstacktrace ();
 }
	}

}

(3) need to improve the point

1, client and server-side IO exception, such as no processing, the program is not logically robust

2, for serialization and deserialization after the transmission of messages, the sender sent the message completed, the receiver end of the message received how to define. Here is completed, if it is not the analysis of the receive and send to complete it is relatively simple, the complexity lies in how to determine the large amount of data in the case, according to the corresponding agreement to parse it out. Need an extensible data protocol, follow-up I will invent a wheel to solve the following problems: A, according to the development of the separator symbol to parse the data B: To resolve the serialization and deserialization of the data C:java object in terms of "message length" "Message content" This variable length message

3, listening and processing op_accept, Op_read, op_write events How the number of threads allocated to achieve efficient synergy, can be based on business needs to deploy ratios to achieve optimal performance.

4, listening to op_write operation is more troublesome, as long as the write buffer is not full can always write, the need for frequent deletion and registration of Op_write events, greatly affecting performance, how to optimize.

5, in a number of connections at the same time to the service side, a selector is enough, a selector can manage how many channel it. In addition, read the message from the channel, write the message to the channel must use the Subreactor to deal with it. It's not good to deal with Workthread.

6, TCP protocol trouble is that receiving/sending data does not guarantee orderly, in the client synchronization waiting for the service side response, how to the asynchronous processing of the server to correspond to the client synchronization processing. Of course, the client can also be synchronous or asynchronous access to the server.

7, how to avoid the business program data and NiO buffer between the copy, reduce performance. How to use one of the Bytebuffer content from the check-in, avoid copy to reduce performance.

These questions are raised, I combine a lot of information on the Internet, also referred to the principles of Mina, Netty article, but did not read the source code of these two frames, I thought, put these problems first from the theoretical solution, and then use their own code to practice, the above examples to plump up, The basic solution to these problems, then to study and compare the specific implementation of Mina, Netty, such a trip down to Java+nio+channel's programming has a holistic understanding. For several years, I want to do this thing, but has been stagnant for a variety of reasons, this time it is necessary to practice, in this blog to put forward this point of view, is that I want to use this statement to tell myself to be sure to go on the end.

so far, I think the best way to learn a frame or a knowledge point is to practice, to invent a wheel of their own ideas, and then simulate the scene to test, and then see how the open source products in the master is how to achieve, the two contrast, their shortcomings are found out, also know how to improve.



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.