SocketChannel_NIO_编程_聊天Demo

 
 

Server端:


package Server;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


public class SeverChannel {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ByteBuffer bb=ByteBuffer.allocate(1024);
        Start(bb);
    }


    public static void Start( ByteBuffer bb) {
  
        ServerSocketChannel ssc = null;
        Selector s = null;
        boolean tag=false;
        try {
            ssc = ServerSocketChannel.open();
            s = Selector.open();
            ssc.socket().bind(new InetSocketAddress(10086));
            ssc.configureBlocking(false);
            ssc.register(s, SelectionKey.OP_ACCEPT);
            while (true) {
                if (s.select() == 0) {
                    System.out.println("Next Loop");
                    continue;
                }
                Iterator<SelectionKey> keys = s.selectedKeys().iterator();
                while (keys.hasNext()) {
                    SelectionKey key = keys.next();
                    if (key.isAcceptable()) {
                        System.out.println(key + "______________Accept");
                        HandleAccept(key,  bb);
                    }
                    if (key.isConnectable())
                        ;
                    //System.out.println(key + "______________Connect");
                    if (key.isReadable()) {
                        //System.out.println(key + "______________Read");
                        HandleRead(key);
                    }
                 if (key.isWritable()) {
                        //System.out.println(key + "______________Write");
                        //HandleWrite(key);
                     if(!tag) {
                         inputThread(key);
                         tag=true;
                     }
                   }


                    keys.remove();
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {


            try {
                ssc.close();
                s.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
    }


    public static void HandleAccept(SelectionKey key, ByteBuffer bb) {


        ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
        SocketChannel sc = null;
        try {
            sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(key.selector(), SelectionKey.OP_READ|SelectionKey.OP_WRITE,bb);
         


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


    public static void HandleRead(SelectionKey key) {


        SocketChannel sc = null;
        sc = (SocketChannel) key.channel();
        ByteBuffer bb=(ByteBuffer) key.attachment();
        try {
                sc.read(bb);
                bb.flip();
                System.out.println("小姐姐说:"+Charset.forName("UTF-8").newDecoder().decode(bb));
                bb.clear();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       


    }
    public static void inputThread(SelectionKey key) {
        SocketChannel sc=(SocketChannel) key.channel();
        ByteBuffer bb=(ByteBuffer) key.attachment();
        new Thread(new Runnable() {
           @Override
         
           public void run() {
               // TODO Auto-generated method stub
               try {  
                System.out.println("Connect with "+sc.getRemoteAddress()+" Sucessed");      
               Scanner scan = new Scanner(System.in);
               while(true){
               String str = scan.nextLine(); 
              
                   bb.put(str.getBytes("UTF-8"));
                   bb.flip();
                   sc.write(bb);
                   bb.clear();
               }
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
               }
               }
           }
                ).start();
   }


//    public static void HandleWrite(SelectionKey key) {
//        SocketChannel sc = null;
//        sc = (SocketChannel) key.channel();
//        ByteBuffer bb = (ByteBuffer) key.attachment();
//        Scanner scan = new Scanner(System.in);
//        String str = scan.nextLine();
//        //while(!str.equals("\n")) {
//        bb.clear();
//        bb.put(str.getBytes());
//        bb.flip();
//        try {
//            sc.write(bb);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//    }

}


Client端:

package Client;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


import javax.sound.midi.VoiceStatus;


public class ClientChannel {


    public static void main(String[] args) {
        //client();
        ByteBuffer bb = ByteBuffer.allocate(1024);
        Start(bb);
    }


    public static void Start(ByteBuffer bb) {
        SocketChannel sc = null;
        Selector s = null;
        try {
            sc = SocketChannel.open();
            s = Selector.open();


            sc.configureBlocking(false);
            sc.connect(new InetSocketAddress("localhost", 10086));
            sc.register(s, SelectionKey.OP_CONNECT, bb);
            boolean tag = false;
            while (true) {
                if (s.select() == 0) {
                    System.out.println("Next Loop");
                    continue;
                }
                Iterator<SelectionKey> keys = s.selectedKeys().iterator();
                SelectionKey key = null;
                while (keys.hasNext()) {
                    key = keys.next();
                    if (key.isConnectable()) {


                        System.out.println("Connectable");
                        sc.finishConnect();
                        key.interestOps(key.OP_WRITE | key.OP_READ);
                    }
                    if (key.isReadable()) {
                        // System.out.println("Read");
                        HandleRead(key);
                    }
                    if (key.isWritable()) {
                        //                        System.out.println("Write");
                        //                        System.out.println(key.interestOps());
                        // HandleWrite(key);
                        if (!tag) {
                            inputThread(key);
                            tag = true;
                        }


                    }


                    keys.remove();
                }


            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (sc != null)
                try {
                    sc.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }


    }


    //    public static void HandleWrite(SelectionKey key) {
    //        SocketChannel sc = null;
    //
    //        sc = (SocketChannel) key.channel();
    //        ByteBuffer bb = ByteBuffer.allocate(1024);
    //        Scanner scan = new Scanner(System.in);
    //        System.out.println("Please Input Some Info:");
    //        String str = scan.nextLine();
    //        //while(!str.equals("\n")) {
    //        bb.clear();
    //        bb.put(str.getBytes());
    //        bb.flip();
    //        try {
    //            sc.write(bb);
    //        } catch (IOException e) {
    //            // TODO Auto-generated catch block
    //            e.printStackTrace();
    //        }
    //
    //    }
    public static void HandleRead(SelectionKey key) {


        SocketChannel sc = null;
        sc = (SocketChannel) key.channel();
        ByteBuffer bb = (ByteBuffer) key.attachment();
        try {
            sc.read(bb);
            bb.flip();
            while (bb.hasRemaining())
                System.out.println(Charset.forName("UTF-8").newDecoder().decode(bb));
            bb.clear();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


    public static void inputThread(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        ByteBuffer bb = (ByteBuffer) key.attachment();
        new Thread(new Runnable() {


            @Override


            public void run() {
                // TODO Auto-generated method stub
                try {
                    System.out.println("Connect with " + sc.getRemoteAddress() + " Sucessed");
                    Scanner scan = new Scanner(System.in);
                    while (true) {
                        String str = scan.nextLine();
                        bb.put(str.getBytes("UTF-8"));
                        bb.flip();
                        sc.write(bb);
                        bb.clear();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();


    }
}


猜你喜欢

转载自blog.csdn.net/qq_15022971/article/details/78793875