Java NIO, which features non-blocking, channel multiplexing, greatly improves the efficiency of TCP communications, and because Java NiO has non-blocking features, a single line can be used to manage multiple links based on this feature. The following program demonstrates a simple simulation of the build of a TCP server and client access without using selector:
1, Server class Server.java
Package com.zws.nio.nosel;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import com.zws.nio.util.niohelper;public class server extends thread{private Serversocketchannel sevchn = null;private socketchannel chn = null;private boolean block = false;private int port;public server (Int port) { This.port = port;init ();} @Overridepublic void run () {while (!isinterrupted ()) {try {// The Accept method here is a non-blocking method that returns null without a client link, whether or not a client link is returned. if ((Chn = sevchn.accept ()) != null) {string msg = niohelper.read (CHN); System.out.println ("server gets msg:" + msg);msg = "Hello client ..."; Niohelper.write (chn, msg); Chn.close ();} else {//do something else}} catch (ioexception e) {e.printstacktrace ();}} /* * Initialize Serversocketchannel, Socketchannel */private void init () {try { Sevchn = serversocketchannel.open (); sevchn.configureblocking (block);//configuration blocking, false: Non-blocking, true: Block Sevchn.socket (). Bind (New inetsocketaddress (port));} catch (ioexception e) {e.printstacktrace ();}} /** * shut Down Server */public void close () {this.interrupt ();if (sevChn != null) Try {sevchn.close ();} catch (ioexception e) {e.printstacktrace ();}} Public static void main (String[] args) {Server server = new Server (9003); Server.start ();//server.close ();}}
2, Client class: Client.java
Package com.zws.nio.nosel;import java.io.ioexception;import java.net.inetsocketaddress;import java.nio.channels.socketchannel;import com.zws.nio.util.niohelper;public class client {public static void main (String[] args) {boolean block = false; Socketchannel chn = null;try {chn = socketchannel.open (); Chn.connect (new Inetsocketaddress ("localhost", 9003)), chn.configureblocking (block);while (true) {//whether to complete the link, non-blocking method. if (Chn.finishconnect ()) {String msg = "Hello server ..."; Niohelper.write (chn, msg); Msg = niohelper.read (CHN); System.out.println ("client gets msg:" + msg); else {//do something else}}} catch (ioexception e) {e.printstacktrace ();} finally {if (Chn != null) Try {chn.close ();} catch (ioexception e) {E.printstacktrace ();}}}
3, Auxiliary class: Niohelper.java
package com.zws.nio.util;import java.io.ioexception;import java.nio.bytebuffer;import java.nio.channels.socketchannel;public class niohelper {public static final string charset_utf8 = "UTF-8";p ublic static void write (SocketChannel chn, string msg) throws ioexception {byte[] bts = msg.getbytes (CHARSET_ UTF8);int len = bts.length; Bytebuffer buffer = bytebuffer.allocate (len + 4); Buffer.put (IntegerUtil.toBytes (len)) ;//The first 4 bytes are the message length buffer.put (BTS); Buffer.flip ();while (buffer.hasremaining ()) chn.write (buffer);} Public static string read (SOCKETCHANNEL CHN) throws ioexception {string msg = null;byte[] bts = new byte[4]; Bytebuffer buffer = bytebuffer.allocate (4);while (chn.read (buffer) == 0) {} Buffer.flip (); Buffer.get (Bts, 0, buffer.remaining ()); Int size = integerutil.toint (BTS);buffer = Bytebuffer.allocate (size);while (chn.read (buffer) == 0) {}buffer.flip ();bts = New byte[size];buffer.get (Bts, 0, buffer.remaining ()); Msg = new string (BTS, CHARSET_UTF8); return msg;}}
4, Auxiliary class: Integerutil.java
package com.zws.nio.util;public class integerutil {/** * int into a 4-byte array * @param value * @return */public static byte[] tobytes (int value) { byte[] bytes = new byte[4]; for (int i = 0; i < 4; i++) { bytes[i] = (Byte) (VALUE&NBSP;>>&NBSP;8&NBSP;*&NBSP;I&NBSP;&&NBSP;0XFF); } return bytes;} /** * byte array conversion int * @param bytes * @return */public static int toint (byte[] bytes) { int value = 0; for (int i = 0; i < bytes.length; i++) { byte item = bytes[i]; value += (ITEM&NBSP;&&NBSP;0XFF) < < (8 * i); } return value;}}
This article is from the "Evan" blog, be sure to keep this source http://wenshengzhu.blog.51cto.com/5151285/1707510
Java NIO (i)