Java TCP Asynchronous Data reception

Source: Internet
Author: User

has been used before. NET to write the service-side program, recently need to switch to the Linux platform, so try to write a data server in Java. TCP asynchronous connections are easy to implement in C #, and there are lots of code to reference on the web. However, the Java asynchronous TCP reference is less, the online routine is blocking multithreading method, because of the high cost of the thread, when the client is more expensive system resources.

Combining the knowledge of the Internet and books, this article gives a code example of the asynchronous reception of data by Java TCP, and gives relevant comments.

/*** Tcpasyncserver.java*/ImportJava.nio.ByteBuffer;Importjava.nio.channels.*;Importjava.net.*;ImportJava.util.Iterator; Public classTcpasyncserver {/*Listening Port*/    intPort = 6000; /*Buffer size*/Bytebuffer Buffer= Bytebuffer.allocate (1024); /*Other related definitions*/Selector Selector;    Serversocketchannel Channel;    ServerSocket socket; /*Start*/     Public voidStart ()throwsException {/*Initialize a selector*/selector=Selector.open (); /*Open channel*/Channel=Serversocketchannel.open (); /*non-blocking mode*/channel.configureblocking (false); /*Native IP*/        //inetaddress IP = inetaddress.getbyname ("127.0.0.1");inetaddress IP =Inetaddress.getlocalhost ();        System.out.println (Ip.tostring ()); /*binding IP and Ports*/inetsocketaddress Address=Newinetsocketaddress (Ip,port); Socket=Channel.socket ();        Socket.bind (address); /*Start Monitoring*/System.out.println ("TCP Server starts listening ...");    Listen (); }    /*Stop*/     Public voidStop ()throwsException {channel.close ();    Selector.close (); }    /*Monitor*/     Public voidListen ()throwsException {/*registering to receive events*/Channel.register (selector,selectionkey.op_accept); /*Infinite Loops*/         while(true) {selector.select (); /*Polling Events*/Iterator iter=Selector.selectedkeys (). iterator ();  while(Iter.hasnext ()) {Selectionkey key=(Selectionkey) iter.next ();                Iter.remove (); /*Event Classification Processing*/                if(Key.isacceptable ()) {Serversocketchannel SSC=(Serversocketchannel) Key.channel (); Socketchannel SC=ssc.accept (); Sc.configureblocking (false);                    Sc.register (selector, selectionkey.op_read); System.out.println ("New terminal connected:" +sc.getremoteaddress ()); }                Else if(Key.isreadable ()) {Socketchannel SC=(Socketchannel) Key.channel (); intRecvcount =sc.read (buffer); if(Recvcount > 0) {                        byte[] arr =Buffer.array (); System.out.println (sc.getremoteaddress ()+ "Send data:" +NewString (arr));                    Buffer.flip (); }                    Else{sc.close ();                } buffer.clear (); }                Else {                }            }        }    }}
/***/Publicclass  server    {publicstatic void throws Exception {        new  tcpasyncserver ();        Tcpserver.start ();    }}

Effect Demo:

1. Sending data using the TCP tool

3. Receiving data

Java TCP Asynchronous Data reception

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.