Java NiO Study Notes (5)

Source: Internet
Author: User

Java NiO socketchannel serversocketchannel and the echo server and client implemented by selector (currently problematic)

Server 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. 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); 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 in system. out. println ("listening for new events... "); 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 ("deal with new accept... "); serversocketchannel Server = (serversocketchannel) Key. channel (); socketchannel SC = server. accept (); SC. configureblocking (false); // register the read event SC. register (S, selectionkey. op_write); system. out. println ("deal with new accept2... ");} 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 (); SC. write (r_bbuf); r_bbuf.flip (); system. out. println (r_bbuf.ascharbuffer (). tostring (); r_bbuf.clear (); system. out. println ("processing completed... "); try {thread. currentthread (). sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}} catch (ioexception e) {e. printstacktrace () ;}} private string getcurrenttime () {return calendar. getinstance (). tostring ();}}

 

Client code:

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; public class testclient {public static void main (string [] ARGs) {New miniclient ("localhost", 1982) ;}} class miniclient {private socketchannel SC; private bytebuffer w_bbuf; 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. isconnected () {system. out. println ("the connection to the server has been lost... ");} 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 (); w_bbuf.flip (); // write data to the buffer zone SC. write (w_bbuf); system. out. println ("data is successfully sent... "); w_bbuf.clear (); try {thread. currentthread (). sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

A picture of thinking in Java, which was just found, has a clear relationship diagram.

 

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.