Introduction to Java IO Multiplexing Technology
Package com. winwill. nio;/*** @ author qifuguang * @ date 15-2-4 */public class TimeServerMain {public static void main (String [] args) throws Exception {// start time server new Thread (new SelectorTimeServer ()). start ();}}
Package com. winwill. nio;/*** @ author qifuguang * @ date 15-2-4 */public class TimeClientMain {public static void main (String [] args) throws Exception {// create 100 clients to connect to the server for (int I = 0; I <100; I ++) {new Thread (new SelectorTimeClient (I + 1 )). start ();}}}
Package com. winwill. nio; 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. text. simpleDateFormat; import java. util. date; import java. util. iterator;/*** @ author qifuguang * @ date 15-2-4 */public class SelectorTimeServe R implements Runnable {private static final String TIME_ORDER = "Query Time"; private Selector selector; private ServerSocketChannel serverChannel; private volatile boolean stop = false;/*** create Selector and ServerSocketChannel, it is set to non-blocking mode and registered to selector. ** @ throws Exception */public SelectorTimeServer () throws Exception {selector = Selector. open (); serverChannel = ServerSocketChannel. open (); serv ErChannel. socket (). bind (new InetSocketAddress (8080); serverChannel. configureBlocking (false); serverChannel. register (selector, SelectionKey. OP_ACCEPT);}/*** round-robin listener selector. * // @ Override public void run () {try {System. out. println ("time server startup! "); While (! Stop) {selector. select (1000); Iterator
Iterator = selector. selectedKeys (). iterator (); while (iterator. hasNext () {SelectionKey key = iterator. next (); iterator. remove (); handleKey (key) ;}} if (selector! = Null) {selector. close () ;}} catch (Exception e) {e. printStackTrace () ;}}/*** processes events of interest to each selector. ** @ param key: The SelectionKey obtained by the listener. */private void handleKey (SelectionKey key) {try {if (key. isValid () {// if the connection is successful if (key. isAcceptable () {// listen to a new client connected to SocketChannel accept = (ServerSocketChannel) key. channel ()). accept (); // establish an accept connection with the client. configureBlocking (false); // set the connection to non-blocking mode acce Pt. register (selector, SelectionKey. OP_READ); // register the connection to selector System. out. println ("new client connection found... ");} if (key. isReadable () {// listen to a client sending a request SocketChannel channel = (SocketChannel) key. channel (); // read the request ByteBuffer buff = ByteBuffer from the client. allocate (1, 1024); int size = channel. read (buff); if (size> 0) {byte [] B = new byte [size]; buff. flip (); buff. get (B); String order = new String (B, "UTF-8"); System. Out. println ("receive client command:" + order); String content = ""; if (order. required signorecase (TIME_ORDER) {content = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "). format (new Date ();} else {content = "command error";} // action is taken based on the request sent from the client, return the processing result to the client doWrite (channel, content);} else if (size <0) {channel. close (); key. cancel () ;}else {;}}} catch (Exception e) {e. printStackTrace () ;}}/*** to the specified SocketCha Nnel sends the specified message. ** @ Param SC refers to the SocketChannel to which a message is sent * @ param content refers to the message to be sent * @ throws Exception */private void doWrite (SocketChannel SC, String content) throws Exception {ByteBuffer buffer = ByteBuffer. allocate (1, 1024); buffer. put (content. getBytes ("UTF-8"); buffer. flip (); SC. write (buffer); if (! Buffer. hasRemaining () {System. out. println ("send a message to the client:" + content );}}}
Package com. winwill. nio; import java.net. inetSocketAddress; import java. nio. byteBuffer; import java. nio. channels. selectionKey; import java. nio. channels. selector; import java. nio. channels. socketChannel; import java. util. iterator;/*** @ author qifuguang * @ date 15-2-4 */public class SelectorTimeClient implements Runnable {private static final String TIME_ORDER = "Query Time"; private SocketChannel Channel; private Selector selector; private volatile boolean stop = false; private Integer index;/*** create Selector, SocketChannel. ** @ param index Client ID. * @ throws Exception */public SelectorTimeClient (Integer index) throws Exception {selector = Selector. open (); channel = SocketChannel. open (); channel. configureBlocking (false); this. index = index;}/*** poll the events that selector is just interested in. * // @ Override public Void run () {try {System. out. println ("Number" + index + "client started! "); // First try to connect to the server asynchronously. If the connection is successful, you only need to register the channel to the READ event of the selector, // READ the results returned by the server. if it fails (the client has sent the sync package to the server, but the server has not returned the ack package, and the physical link has not been established) // register the channel to the selector's CONNECT event, wait for the ack packet returned by the server. if (channel. connect (new InetSocketAddress (8080) {channel. register (selector, SelectionKey. OP_READ); doWrite (channel, TIME_ORDER);} else {channel. register (selector, SelectionKey. OP_CONNECT) ;}while (! Stop) {selector. select (1000); Iterator
Iterator = selector. selectedKeys (). iterator (); while (iterator. hasNext () {SelectionKey key = iterator. next (); SocketChannel SC = (SocketChannel) key. channel (); iterator. remove (); if (key. isValid () {if (key. isReadable () {// listens to readable events and reads the processing results returned by the server. byteBuffer buff = ByteBuffer. allocate (1, 1024); int size = SC. read (buff); if (size> 0) {byte [] B = new byte [size]; buff. flip (); buff. get (B); System. ou T. println ("Number" + index + "client to obtain the server return time:" + new String (B); stop = true;} else if (size <0) {SC. close (); key. cancel () ;}else {;}} if (key. isConnectable () {// listens to the server and returns an ack packet, preparing to complete connection establishment if (SC. finishConnect () {// call this method to establish a physical link connection SC. register (selector, SelectionKey. OP_READ); // register and listen to the READ event doWrite (SC, TIME_ORDER);} else {System. exit (1); // if (selector! = Null) {selector. close () ;}} catch (Exception e) {e. printStackTrace () ;}}/*** sends the specified message to the specified channel. ** @ param channel refers to the channel to which a message is sent * @ param content refers to the message to be sent * @ throws Exception */private void doWrite (SocketChannel channel, String content) throws Exception {ByteBuffer buff = ByteBuffer. allocate (1, 1024); buff. put (content. getBytes ("UTF-8"); buff. flip (); channel. write (buff); if (! Buff. hasRemaining () {System. out. println ("the" + index + "client successfully sent the request to the server:" + content );}}}