Java.nio.channels-based programming practice

Source: Internet
Author: User
Tags getmessage

Service-side code
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.util.iterator;import Java.util.set;import Java.util.concurrent.timeunit;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class NIOSocketServer Extends Thread {private static final Logger LOG = Loggerfactory.getlogger (niosocketserver.class);p rivate static final Str ing CHARSET = "UTF-8";p rivate static final int buffer_size = 1024;private static final int fail_try_num = 3;private Select or selector;private serversocketchannel ssc;private static niosocketserver server;/** * Program Entry * * @param args */public sta tic void Main (string[] args) {server = new niosocketserver (); try {//Server.setdaemon (TRUE); Server.initserver (); Server.start ();} catch (Exception e) {//If an exception occurs, close the client server.stopserver () directly; System.exit (1);}} @Overridepublic VOID run () {int failnum = 0;while (true) {try {int select = Selector.select (), if (select > 0) {set<selectionkey> ke ys = 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 ();}}} catch (Exception e) {failnum++;if (Failnum > Fail_try_num) {server.stopserver ();}}} /** * Initialize server-side program, start listening port * * @throws ioexception */private void Initserver () throws IOException {selector = Selector.open () ; SSC = Serversocketchannel.open (); ssc.configureblocking (false); Ssc.socket (). bind (New Inetsocketaddress (2181)); Ssc.register (selector, selectionkey.op_accept);} /** * Stop Server * * @throws ioexception */private void Stopserver () {try {if (selector! = null && selector.isopen ()) {Selector.close ();} if (SSC! = null && ssc.isopen ()) {ssc.close ();}} catch (IOException e) {log.info ("Close Server failed:" + e.getmessage ());}} /** * Processing of new client connections * * @param key * @throws ioexception */private void doacceptable (Selectionkey key) throws IOException {Serversocketchannel TMPSSC = (serversocketchannel) key.channel (); Socketchannel ss = Tmpssc.accept (); ss.configureblocking (false); Ss.register (selector, Selectionkey.op_read | Selectionkey.op_write);} /** * Connected * * @param key */private void doconnectable (Selectionkey key) {Log.info ("Connect is OK");} /** * Write message to Client * * @param key * @throws ioexception */private void Dowritemessage (Selectionkey key) throws Exception {Sock Etchannel sc = (socketchannel) key.channel (); Bytebuffer buffer = bytebuffer.wrap ("Server write msg to client". GetBytes (CHARSET)), while (Buffer.hasremaining ()) { Sc.write (buffer);} TimeUnit.SECONDS.sleep (1);}  /** * @param key * @throws ioexception */private void Doreadmessage (Selectionkey key) throws Exception {Socketchannel sc = (Socketchannel) Key.channel (); Bytebuffer BB = byTebuffer.allocate (buffer_size); int read = Sc.read (BB), while (Read > 0) {bb.flip (); byte[] Barr = new Byte[bb.limit ()];b B.get (Barr); Log.info ("server read msg from client:" + new String (Barr, CHARSET)); Bb.clear (); read = Sc.read (BB);} TimeUnit.SECONDS.sleep (1);}}
Client Code
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; Import Java.util.concurrent.timeunit;import Org.slf4j.logger;import Org.slf4j.loggerfactory;public class Niosocketclient extends Thread {private static final Logger LOG = Loggerfactory.getlogger (Niosocketclient.class); private static final String CHARSET = "UTF-8";p rivate static final int buffer_size = 1024;private static final int fail_tr   Y_num = 3;private Socketchannel socketchannel;private Selector selector;private static niosocketclient client;/** * Program Entry * * @param args */public static void main (string[] args) {client = new niosocketclient (); try {client.initclient (); Client.s Tart ();//Client.setdaemon (TRUE);} catch (Exception e) {//If an exception occurs, close the client directly ClieNt.close ();}} public void Run () {int failnum = 0;while (true) {try {writemessage (); int select = Selector.select (); SYSTEM.OUT.PRINTLN (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 ();}}} catch (Exception e) {//If more than three occurrences of the exception occur, close the client failnum++;if (Failnum > Fail_try_num) {client.close (); System.exit (1);}}} public void Readmessage (Selectionkey sk) throws Exception,unsupportedencodingexception {Socketchannel CURSC = ( Socketchannel) Sk.channel (); Bytebuffer buffer = bytebuffer.allocate (buffer_size), while (Cursc.read (buffer) > 0) {buffer.flip (); Log.info ("read message from server:" + New String (Buffer.array (), CHARSET)); Buffer.clear ();} TimeUnit.SECONDS.sleep (1);} public void Writemessage () throws Exception {String ss = ' Client write msg to server '; Bytebuffer buffer = Bytebuffer.wrap (Ss.getbytes (CHARSET)); wHile (Buffer.hasremaining ()) {socketchannel.write (buffer);} TimeUnit.SECONDS.sleep (1);} public void Initclient () throws IOException, closedchannelexception {inetsocketaddress addr = new Inetsocketaddress (2181 ); Socketchannel = Socketchannel.open (); selector = Selector.open (); socketchannel.configureblocking (false); Socketchannel.register (selector, selectionkey.op_read);//Connect to Serversocketchannel.connect (addr); Socketchannel.finishconnect ()) {Log.info ("Check finish Connection");}} /** * Stop client */private void Close () {try {if (selector! = null && selector.isopen ()) {selector.close ()}; if (Socketchannel! = null && socketchannel.isopen ()) {socketchannel.close ();}} catch (IOException e) {log.info ("Shutdown client failed:" + e.getmessage ());}}}

Java.nio.channels-based programming practice

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.