Java nio implements non-blocking Socket communication instances

Source: Internet
Author: User

Package com. java. xiong. net17; import java. io. IOException; import java.net. inetSocketAddress; import java. nio. byteBuffer; import java. nio. channels. channel; 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; public class NServer {// selectorprivate Selec used to detect all Channel states Tor selector = null; static final int PORT = 30000; // defines the private Charset charse = Charset, which implements encoding and decoding. forName ("GBK"); public void init () throws IOException {selector = Selector. open (); // open an unbound ServerSocketChannel through the open method. It is ServerSocketChannel server = ServerSocketChannel. open (); InetSocketAddress isa = new InetSocketAddress ("127.0.0.1", PORT); // bind the ServerSocketChannel to the specified IP address server. bind (isa); // set Sets serverSocket to work in non-blocking mode. configureBlocking (false); // register the server with the specified selector Object server. register (selector, SelectionKey. OP_ACCEPT); while (selector. select ()> 0) {// process each selected SelectionKeyfor (SelectionKey sk: selector. selectedKeys () {// Delete the SelectionKeyselector being processed from the selected Kye set on the selector. selectedKeys (). remove (sk); // if the Channel corresponding to sk contains the client connection request if (sk. isAcceptable () {// call the accept method to receive connections and generate Socke for the server segment TChennalSocketChannel SC = server. accept (); // sets the non-blocking mode SC. configureBlocking (false); // register the SocketChannel to selectorsc. register (selector, SelectionKey. OP_READ);} // if the Channel corresponding to sk has data, read if (sk. isReadable () {// gets the Channel of the SelectionKey pair to the bank. The Channel has the scaled data SocketChannel SC = (SocketChannel) sk. channel (); // define the remarks. Execute ByteBufferByteBuffer buff = ByteBuffer to read the data source. allocate (1024); String content = ""; // start to read data try {w Hile (SC. read (buff)> 0) {buff. flip (); content + = charse. decode (buff);} System. out. println ("read data:" + content); // set the Channel corresponding to sk to prepare for the next sk read. interestOps (SelectionKey. OP_READ);} // if an exception occurs to the bank Channel of the sk captured, it indicates that the Client corresponding to the // Channel has a problem, so the catch (IOException io) is canceled from the Selector) {// Delete the specified SelectionKeysk from Selector. cancel (); if (sk. channel ()! = Null) {sk. channel (). close () ;}/// if the content length is greater than 0, the consecutive days information is not empty if (content. length ()> 0) {// traverse all SelectionKeyfor (SelectionKey key: selector. keys () {// obtain the ChannelChannel targerChannel = key. channel (); // if the Channel is a SocketChannel object if (targerChannel instanceof SocketChannel) {// write the read content to the Channel SocketChannel dest = (SocketChannel) targerChannel; dest. write (charse. encode (content) ;}}}}} public static void main (String [] args) throws IOException {new NServer (). init ();}}


 

Package com. java. xiong. net17; 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. socketChannel; import java. nio. charset. charset; import java. util. listener; public class NClient {// defines the Selector object private Selector selector = null for Sockethannel detection; static final int PORT = 30000; // defines the character set private Charset charset = Charset for encoding processing. forName ("GBK"); // client SocketChannelprivate SocketChannel SC = null; public void init () throws IOException {selector = Selector. open (); InetSocketAddress isa = new InetSocketAddress ("127.0.0.1", PORT); // call the open static method to create SocketChannelsc = SocketChannel to connect to the specified host. open (isa); // sets the SC to work in a non-blocking mode. configureBlocking (false); // register the SocketChannel object to the specified Selectorsc. register (selector, SelectionKey. OP_READ); // start the new ClientThread () thread for reading server data (). start (); // create the keyboard input stream Scanner scan = new keyboard (System. in); while (scan. hasNextLine () {// read the input String line of the keyboard = scan. nextLine (); // output the content of the keyboard to SC in SocketChanenel. write (charset. encode (line) ;}}// defines the private class ClientThread extends Thread {@ Overridepublic void run () {try {while (selector. select ()> 0) {// traverse the SelectionKeyfor (SelectionKey sk: selector. selectedKeys () {// Delete the SelectionKeyselector being processed. selectedKeys (). remove (sk); // if the Channel corresponding to the SelectionKey contains readable data if (sk. isReadable () {// use NIO to read data in the Channel SocketChannel SC = (SocketChannel) sk. channel (); String content = ""; ByteBuffer bff = ByteBuffer. allocate (1, 1024); while (SC. read (bff)> 0) {SC. read (bff); bff. flip (); content + = charset. decode (bff);} // print the read content System. out. println ("chat information:" + content); sk. interestOps (SelectionKey. OP_READ) ;}}} catch (IOException io) {io. printStackTrace () ;}} public static void main (String [] args) throws IOException {new NClient (). init ();}}

 

Related Article

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.