Java TCP NIO Example__java

Source: Internet
Author: User

Server End:

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;  /** * Create by Leon on 2017/4/7 */public class Server {public static void main (string[] args) throws IOException
        {//Open event listener Selector Selector = Selector.open ();
        Open Channel Serversocketchannel SSC = Serversocketchannel.open ();
        Bind the listening port through the socket Ssc.socket (). bind (New Inetsocketaddress (9527));
        Set to Non-blocking ssc.configureblocking (false);
        Registering Connection Events Ssc.register (selector, selectionkey.op_accept);
            while (true) {int keys = selector.select (1000); if (Keys > 0) {//There is a new event for (Selectionkey Key:selector.selectedKeys ()) {if key.
     Isacceptable ()) {//Get Serversocketchannel                   Serversocketchannel channel = (Serversocketchannel) key.channel ();
                        Get socketchannel Socketchannel Socketchannel = channel.accept ();
                        if (Socketchannel = = null) {continue;
                        } socketchannel.configureblocking (FALSE);
                    Socketchannel.register (selector, selectionkey.op_read); else if (key.isreadable ()) {//define buffer Bytebuffer Bytebuffer = Bytebuff
                        Er.allocate (1024);
                        Get Socketchannel Socketchannel Socketchannel = (socketchannel) key.channel ();
                        Read the data into the buffer Socketchannel.read (bytebuffer);
                        Convert buffer to byte array byte[] array = Bytebuffer.array (); String msg = new String (array). tRim ();
                        System.out.println ("Receive msg:" + msg);
                            if ("Exit". Equalsignorecase (msg)) {socketchannel.close ();
                            Ssc.close ();
                            Selector.close ();
                        System.exit (0); //Get the Buffer,wrap method for sending messages Bytebuffer out = Bytebuffer.wrap (Msg.getbytes ())
                        ;
                    Write channel socketchannel.write (out);
            }//Note here to remove the key Selector.selectedkeys (). Clear ();
 }
        }
    }
}

Client side:

Import Org.apache.commons.lang.StringUtils;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import java.net.InetSocketAddress;
Import Java.nio.ByteBuffer;
Import Java.nio.channels.SelectionKey;
Import Java.nio.channels.Selector;

Import Java.nio.channels.SocketChannel;  /** * Create by Leon on 2017/4/7 */public class Client {public static void main (string[] args) throws IOException
        {//Open event listener Selector Selector = Selector.open ();
        Get socketchannel Socketchannel Socketchannel = Socketchannel.open ();
        Set connection to server IP and Port socketchannel.connect (new Inetsocketaddress ("127.0.0.1", 9527));
        Set non-blocking socketchannel.configureblocking (false);
        Registering Connection Events Socketchannel.register (selector, selectionkey.op_connect);
        BufferedReader in = new BufferedReader (new InputStreamReader (system.in)); while (true) {if (socketchannel.isconnected ()) {//Connect first to send message
                String command = In.readline ();
                Socketchannel.write (Bytebuffer.wrap (Command.getbytes ()));
                    if (Stringutils.isnotblank command && exit. Equalsignorecase (command)) {in.close ();
                    Selector.close ();
                    Socketchannel.close ();
                System.exit (0);
            } int keys = Selector.select (1000); if (Keys > 0) {for (Selectionkey Key:selector.selectedKeys ()) {if (Key.isconnec Table ()) {///connect//Get Socketchannel Socketchannel channel = (socketchannel
                        ) Key.channel ();
                        Channel.configureblocking (FALSE);
                        Channel.register (selector, selectionkey.op_read);
                    Channel.finishconnect ();
           else if (key.isreadable ()) {//define Buffer             Bytebuffer Bytebuffer = bytebuffer.allocate (1024);
                        Get Socketchannel Socketchannel channel = (Socketchannel) key.channel ();
                        Read the buffer in Channel.read (Bytebuffer);
                        Convert to byte array byte[] array = Bytebuffer.array ();
                        String msg = new String (array). Trim ();
                    System.out.println ("Receive from Server:" + msg);
            }//Note here to remove the key Selector.selectedkeys (). Clear ();
 }
        }
    }
}


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.