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