NIO 예제 프로그램

11816 단어 Java
1. 클 라 이언 트 프로그램
package cn.fzmili.archetype.nio;

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.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 *      2-4       
 *
 * @author fzmili
 *       : start()---------       。         main     。start()          。
 * main()----------       。
 */
public class EchoClient {

    private InetSocketAddress address;
    private ByteBuffer wBuffer = ByteBuffer.allocate(1024);
    private ByteBuffer rBuffer = ByteBuffer.allocate(1024);
    private Charset charset = Charset.forName("UTF-8");//         

    public EchoClient(String host, int port) {
        this.address = new InetSocketAddress(host, port);
    }

    public EchoClient(InetSocketAddress address) {
        this.address = address;
    }

    public void start() throws Exception {//       。
        ///   //
        final SocketChannel channel;
        channel = SocketChannel.open();//      。
        //channel.configureBlocking(false);//        ,         
        channel.connect(address);//               ,         false,             
        //     
        if(channel.isConnectionPending())
            channel.finishConnect();//      ,     ,        ,       ,    。
        if(!channel.isConnected()){
             System.out.println("connecting fail");
             return;
        }
        //      
        System.out.println("Connecting Success!");
        Scanner scanner = new Scanner(System.in);//scanner          。
        String text=scanner.nextLine();//         。
        text+='
';// scanner.nextLine() , 。 System.out.println(" :"+text); scanner.close(); System.in.close(); // 。 wBuffer.put(charset.encode(text)); wBuffer.flip(); channel.write(wBuffer); int readBytes=channel.read(rBuffer);// , System.out.println(" :" + getString(rBuffer)); rBuffer.clear(); channel.close(); } public static String getString(ByteBuffer buffer) { String string = ""; try { for (int i = 0; i < buffer.position(); i++) { string += (char) buffer.get(i);// , 。 } return string; } catch (Exception ex) { ex.printStackTrace(); return ""; } } public static void main(String[] args) throws NumberFormatException { InetSocketAddress address; switch (args.length) { case 0:// IP, , address = new InetSocketAddress("127.0.0.1", 9999); break; case 2:// , , { String ip = args[0]; int port = Integer.parseInt(args[1]); address = new InetSocketAddress(ip, port); } default:// System.err.println("Usage: " + EchoClient.class.getSimpleName() + " "); return; } try { new EchoClient(address).start(); } catch (Exception e) { e.printStackTrace(); } System.out.println("--- ----"); } }

2. 서버 프로그램
package cn.fzmili.archetype.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class EchoServer {

    private InetSocketAddress address;
    private final int bufferSize = 2048;

    public EchoServer(String host, int port) {
        this.address = new InetSocketAddress(host, port);
    }

    public EchoServer(InetSocketAddress address) {
        this.address = address;
    }

    public void start() {
        ///init()   
        Selector selector = null;
        try {
            //  Channel Selector
            ServerSocketChannel channel = ServerSocketChannel.open();
            selector = Selector.open();
            channel.configureBlocking(false);//         
            channel.bind(this.address);
            /*
            * Channel   selector,         
            * 4   :electionKey.OP_CONNECT  SelectionKey.OP_ACCEPT  SelectionKey.OP_READ    SelectionKey.OP_WRITE 
            *OP_CONNECT----     ,
            *OP_ACCEPT-----     
            *OP_READ & OP_WRITE--------   /     
             */
            channel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("Server started .... port:" + address.getPort());
        } catch (Exception e) {
            System.out.println("Error-" + e.getMessage());
            return;
        }
        //    ///
        Map buffers = new HashMap<>();//       Channel   ByteBuffer,    。
        try {
            int id = 0;
            while (true) {//                 。
                Thread.sleep(1 * 1000);
                /*
                *  ,         。
                *                。         Channel。
                *  selector      channell。            。
                *select()      ,       
                 */
                selector.select();
                ///  init()     /
                Set readySelectionKey = selector.selectedKeys();
                Iterator it = readySelectionKey.iterator();
                //       
                while (it.hasNext()) {
                    SelectionKey channelKey = it.next();
                    //Accept---------     TCP  
                    if (channelKey.isAcceptable()) {
                        /*
                        *          ,
                        *        (  ),              ,            
                        *      Channel  Selector.channel()   。SelectionKey       。
                         */
                        ServerSocketChannel channel = (ServerSocketChannel) channelKey.channel();
                        channel.accept()
                                .configureBlocking(false)
                                .register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE)// selector  channel,     Chanenl   SelectionKey, Key  Channel   ,   Channel。
                                .attach(++id);// SelectionKey      ,   Key   Channel,    Channel  。
                        /*
                                       :
                        channel.accept();
                        channel.configureBlocking(false);
                        SelectionKey key=channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);// selector  channel,     Chanenl   SelectionKey, Key  Channel   ,   Channel。
                        key.attach(++id);// SelectionKey      ,   Key   Channel,    Channel  。
                        
                         */
                        buffers.put(id, ByteBuffer.allocate(bufferSize));//            ,  Channel    。
                        System.out.println("ChannelID:" + id+"\tConnected");
                    }
                    if (channelKey.isReadable()) {//    ,   Channel      ,        Channel。
                        SocketChannel clientChannel = (SocketChannel) channelKey.channel();
                        ByteBuffer buf = buffers.get((Integer) channelKey.attachment());
                        try {
                            int readBytes = clientChannel.read(buf);
                            if(readBytes==-1) continue;// read=-1        ,         。
                            System.out.print("ChannelID:" + channelKey.attachment()+ "\tInput");
                            System.out.print("\tReadBytes:" + readBytes);
                            System.out.println("\tContent:" + getString(buf));//getString      ,       。
                        } catch (Exception e) {
                            clientChannel.close();
                            channelKey.cancel();
                            System.out.println("channelID:"+channelKey.attachment()+"\tClosed");
                            continue;
                        }

                    }
                    if (channelKey.isWritable()) {//    
                        // System.out.println(channelKey.attachment()+ " -      ");
                        SocketChannel clientChannel = (SocketChannel) channelKey.channel();
                        ByteBuffer buf = buffers.get((Integer) channelKey.attachment());
                        /*                
                        *buf.position----------           
                        *buf.get(index)------------          。
                         */
                        if (buf.position() > 0) {//         ByteBuffer    ,       。
                            if (buf.get(buf.position() - 1) == '
') { buf.flip(); clientChannel.write(buf); buf.clear(); } } } // removed , , // removed , .next() remove it.remove(); } } } catch (Exception e) { // TODO: handle exception System.out.println("Error - " + e.getMessage()); e.printStackTrace(); } finally { if (selector != null) { try { selector.close(); } catch (IOException e) { System.out.println("Error-" + e.getMessage()); e.printStackTrace(); } } } } // , 。 public static String getString(ByteBuffer buffer) { String string = ""; try { for (int i = 0; i < buffer.position(); i++) { string += (char) buffer.get(i);// , 。 } return string; } catch (Exception ex) { ex.printStackTrace(); return ""; } } public static void main(String[] args) throws Exception { InetSocketAddress address; switch (args.length) { case 0:// IP, , address = new InetSocketAddress("127.0.0.1", 9999); break; case 1:// (IP ) { // ( , NumberFormatException) int port = Integer.parseInt(args[0]); address = new InetSocketAddress(9999); break; } case 2:// , , { String ip = args[0]; int port = Integer.parseInt(args[0]); address = new InetSocketAddress(ip, port); } default:// System.err.println("Usage: " + EchoServer.class.getSimpleName() + " "); return; } new EchoServer(address).start(); } }

좋은 웹페이지 즐겨찾기