Java NiO implements socket asynchronous communication (correct the content in Java NiO Practice Note 5)

Source: Internet
Author: User

Original error version see: http://blog.csdn.net/tsyj810883979/article/details/6877216

The encoding and decoding issues are taken into account on the basis of the original, and two important methods for message sending are neglected.

Public abstract int write (bytebuffer SRC) writes the byte sequence from the given buffer to this channel.
Public abstract int read (bytebuffer DST) reads the byte sequence from this channel into the given buffer zone.

The following code may cause a problem when closing the connection. The server can be disconnected from the client, but the client does not exit after being disconnected. An exception occurs when you perform another operation.

 

Server code implementation:

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. calendar; import Java. util. iterator; public class testserver {public static void main (string [] ARGs) {New thread (New echoserver (1982 )). start () ;}} class echoserver implements runnable {// The port number to be listened to private int port; // generate a signal monitor private selector S; // read buffer private bytebuffer r_bbuf = bytebuffer. allocate (1024); Private bytebuffer w_bbuf; Public echoserver (INT port) {This. port = port; try {S = selector. open ();} catch (ioexception e) {e. printstacktrace () ;}@ overridepublic void run () {try {// generate an instance object for the serverscoket channel to listen for possible Io events serversocketchannel SSC = serversocketchannel. open (); // set the channel to async SSC. configureblocking (false); // bind to a specified port SSC. socket (). BIND (New inetsocketaddress (port); // register a specific type of event to the SSC on the signal monitor. register (S, selectionkey. op_accept); system. out. println ("the server has been launched... "); While (true) {// The execution will be blocked until an event occurs S. select (); iterator <selectionkey> it = S. selectedkeys (). iterator (); While (it. hasnext () {selectionkey key = it. next (); // key defines four different forms of operation switch (key. readyops () {Case selectionkey. op_accept: dealwithaccept (key); break; Case selectionkey. op_connect: break; Case selectionkey. op_read: dealwithread (key); break; Case selectionkey. op_write: break;} // The current event is removed after processing is completed to avoid repeated it processing. remove () ;}} catch (ioexception e) {e. printstacktrace () ;}}// process the event private void dealwithaccept (selectionkey key) that receives the connection {try {system. out. println ("new client request connection... "); serversocketchannel Server = (serversocketchannel) Key. channel (); socketchannel SC = server. accept (); SC. configureblocking (false); // register the read event SC. register (S, selectionkey. op_read); system. out. println ("client connection successful... ");} catch (ioexception e) {e. printstacktrace () ;}// process the message sent from the client and handle the read event private void dealwithread (selectionkey key) {try {socketchannel SC = (socketchannel) Key. channel (); system. out. println ("read data"); r_bbuf.clear (); // read the byte sequence from this channel into the given buffer r_bbufsc.read (r_bbuf); r_bbuf.flip (); string MSG = charset. forname ("UTF-8 "). decode (r_bbuf ). tostring (); If (MSG. equalsignorecase ("time") {w_bbuf = bytebuffer. wrap (getcurrenttime (). getbytes ("UTF-8"); SC. write (w_bbuf); w_bbuf.clear ();} else if (MSG. equalsignorecase ("bye") {SC. write (bytebuffer. wrap ("disconnected from the server ". getbytes ("UTF-8"); SC. socket (). close ();} else {SC. write (bytebuffer. wrap (MSG. getbytes ("UTF-8");} system. out. println (MSG); system. out. println ("processing completed... "); r_bbuf.clear (); try {thread. currentthread (); thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace () ;}} catch (ioexception e) {e. printstacktrace () ;}} private string getcurrenttime () {calendar date = calendar. getinstance (); string time = "current server time:" + date. get (calendar. year) + "-" + date. get (calendar. month) + 1 + "-" + date. get (calendar. date) + "" + date. get (calendar. hour) + ":" + date. get (calendar. minute) + ":" + date. get (calendar. second); return time ;}}

 

Client code implementation:

Import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. inetsocketaddress; import Java. NIO. bytebuffer; import Java. NIO. channels. socketchannel; import Java. NIO. charset. charset; public class testclient {public static void main (string [] ARGs) {New miniclient ("localhost", 1982) ;}} class miniclient {private socketchannel SC; private bytebuffer w_bbuf; private B Ytebuffer r_bbuf = bytebuffer. allocate (1024); Public miniclient (string host, int port) {try {inetsocketaddress remote = new inetsocketaddress (host, Port); SC = socketchannel. open (); SC. connect (remote); If (SC. finishconnect () {system. out. println ("A connection has been established with the server... ");} while (true) {If (! SC. socket (). isconnected () {system. out. println ("the connection to the server has been lost... "); return;} bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); string STR = BR. readline (); system. out. println ("reads a row of data and starts sending... "); w_bbuf = bytebuffer. wrap (Str. getbytes ("UTF-8"); // write data in the buffer to the channel SC. write (w_bbuf); system. out. println ("data is successfully sent... "); w_bbuf.clear (); system. out. println ("receiving server response message... "); try {thread. currentthread (); thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();} r_bbuf.clear (); // read the byte sequence from this channel into the given buffer r_bbufsc.read (r_bbuf); r_bbuf.flip (); string MSG = charset. forname ("UTF-8 "). decode (r_bbuf ). tostring (); system. out. println (MSG) ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

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.