Java NIO Simple Example __java

Source: Internet
Author: User

Server side:

Package Niot;
Import java.io.IOException;
Import java.net.InetSocketAddress;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.SelectionKey;
Import Java.nio.channels.Selector;
Import Java.nio.channels.ServerSocketChannel;
Import Java.nio.channels.SocketChannel;
Import Java.nio.charset.Charset;

Import Java.util.Iterator;

	public class NIOServer1 {//local character set private static final String Localcharsetname = "UTF-8";

	The port on which the local server listens private static final int listenning_port = 8888;

	Buffer size private static final int buffer_size = 1024;

	Timeout, unit milliseconds private static final int TimeOut = 3000; public static void Main (string[] args) throws IOException {//Creates a service socket channel that listens on the local port. and set to non-blocking mode Serversocketchannel

		Serverchannel = Serversocketchannel.open ();
		Serverchannel.socket (). bind (New Inetsocketaddress (Listenning_port));

		Serverchannel.configureblocking (FALSE);
		Create a selector and register the serverchannel above it Selector Selector = Selector.open (); Serverchannel.register (Selector, SelectionKey.op_accept);
				while (true) {//waits for a channel ready if (Selector.select (TimeOut) = = 0) {System.out.println (".");
			Continue

			}//Get the key iterator for the ready channel iterator<selectionkey> keyiter = Selector.selectedkeys (). iterator ();
				Use iterators to traverse the Ready channel while (Keyiter.hasnext ()) {Selectionkey key = Keyiter.next (); This situation is a client-side connection to prepare a clientchannel with which the communication if (Key.isacceptable ()) {Socketchannel Clientchannel = (Serversocketchan
					Nel) key.channel ()). Accept ();
					Clientchannel.configureblocking (FALSE);
				Clientchannel.register (selector, Selectionkey.op_read, Bytebuffer.allocate (buffer_size)); ////client has write-time if (key.isreadable ()) {//access channel Socketchannel Clientchannel = (socketchannel) key.c

					Hannel ();
					The main index value of the reset buffer is obtained bytebuffer buffer = (bytebuffer) key.attachment ();

					Buffer.clear ();

					Read the number of bytes read to get a long bytesread = clientchannel.read (buffer); if (bytesread = = 1) {//no content is read ClientchAnnel.close ();
						else {//prepare buffer as data outgoing state buffer.flip (); Gets the byte string (decoded using Charset) string receivedstring = Charset. forname (Localcharsetname). Newdecoder (). Decode (BU

						Ffer). toString ();

						The console prints out SYSTEM.OUT.PRINTLN ("Receive information:" + receivedstring); Ready to send the text String sendstring = "Hello, client."

						Have received your message "+ receivedstring;

						The string encoding to be sent (encoded using charset) is then wrapped buffer = Bytebuffer.wrap (Sendstring.getbytes (localcharsetname));

						Send back Clientchannel.write (buffer); Set to prepare for next read or write Key.interestops (Selectionkey.op_read |
					Selectionkey.op_write);
			} keyiter.remove ();
 }
		}

	}
}

Client:

Package Niot;

Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.Socket;
Import java.net.UnknownHostException;
Import Java.util.Scanner;

public class Nioclient1test {public

	static void Main (string[] args) throws Unknownhostexception,
			IOException { C10/>socket s = new Socket ("localhost", 8888);

		InputStream instream = S.getinputstream ();
		OutputStream OutStream = S.getoutputstream ();

		Output
		PrintWriter out = new PrintWriter (OutStream, true);
		Out.println ("Getpublickey hello.") ");
		Out.flush ();

		S.shutdownoutput ()//Output end

		//input
		Scanner in = new Scanner (instream);

		StringBuilder sb = new StringBuilder ();
		while (In.hasnextline ()) {
			String line = In.nextline ();
			Sb.append (line);

		String response = sb.tostring ();
		System.out.println ("response=" + response);

	}


Run results

Service side:

.
Received information: Getpublickey hello.

.

Client:

response= Hello, client. have received your message Getpublickey hello.


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.