NIO 포트 전송 실현

package example;
/**
 *      
 */
//import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
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;
public class myServer {
    public static final int PORTClient = 8085;
    public static final int PORTDevice = 8081;
    protected static HashMap<String,SelectionKey> map = new HashMap<String, SelectionKey>();
    //     
    protected Selector selector;
    protected Selector selector_device;
    int clientCount;
    int deviceCount;
    public myServer() throws Exception {
            //     socket selector
            selector = Selector.open();
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(PORTClient)); // port
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);// register         
            p("Server localhost:" + PORTClient + " started. waiting for clients. ");
              
            //      
            selector_device=Selector.open();
            ServerSocketChannel serverSocketChannelDevice = ServerSocketChannel.open();
            serverSocketChannelDevice.socket().bind(new InetSocketAddress(PORTDevice));
            serverSocketChannelDevice.configureBlocking(false);
            serverSocketChannelDevice.register(selector_device, SelectionKey.OP_ACCEPT);
            p("Server localhost:" + PORTDevice + " started. waiting for Device. ");
            Client client=new Client();
            Device device=new Device();
            device.run();
            while (true) {
                  
                  
                client.run();
                      
            }
        }
    class Client implements Runnable{
        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                // selector   。select()    ,        ,       
                selector.select();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                  
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // hashmap.put(, selectionKey);
                iterator.remove(); //      
                //          。(    ,               ,        )
                try {
                    handleSelectionKey(selectionKey);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        public void start() {
            // TODO Auto-generated method stub
              
        }
          
    }
    class Device implements Runnable
    {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //
            try {
                selector_device.select();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Iterator<SelectionKey> iteratorDevice = selector_device.selectedKeys().iterator();
            while (iteratorDevice.hasNext()) {
                SelectionKey selectionKeyDevice = iteratorDevice.next();
                System.out.println(selectionKeyDevice);
                // hashmap.put(, selectionKey);
                iteratorDevice.remove(); //      
                //          。(    ,               ,        )
                try {
                    handleDevice(selectionKeyDevice);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        public void start() {
            // TODO Auto-generated method stub
              
        }
          
    }
    //      
    private void handleDevice(SelectionKey selectionKeyDevice) throws IOException {
        // TODO Auto-generated method stub
        if (selectionKeyDevice.isAcceptable()) {
            //       
            deviceCount++;
            System.out.println(deviceCount);
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKeyDevice.channel();
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            Socket socket = socketChannel.socket();
            //        OP_READ  SelectionKey,         
            SelectionKey key = socketChannel.register(selector_device, SelectionKey.OP_READ);
            System.out.println(key);
            String str=socket.getRemoteSocketAddress().toString();
            String [] strs = str.split("[:]");
            //        map
            map.put(strs[0], key);
            System.out.println(map.get(socket.getRemoteSocketAddress()));
            System.out.println(socket.getInetAddress().getHostAddress());
            key.attach("  " + deviceCount + "       [" + socket.getRemoteSocketAddress() + "]: ");
            p(key.attachment() + "\t[connected] =========================================");
            } else if (selectionKeyDevice.isReadable()) {
                //      
                ByteBuffer byteBufferD = ByteBuffer.allocate(100);
                SocketChannel socketChannel = (SocketChannel) selectionKeyDevice.channel();
                try {
                    int len = socketChannel.read(byteBufferD);
                    if (len > 0) {
                        byteBufferD.flip();//flip()                 ,    limit   position    ,   position    0   
                        socketChannel.write(byteBufferD);
                        //socketChannelDevice.write(byteBuffer);
   
                    } else {
                        //     ,   socketChannel
                        p(selectionKeyDevice.attachment() + "read finished. close socketChannel. ");
                        socketChannel.close();
                    }
                } catch (Exception e) {
                    //   read    ,        ,     socketChannel
                    e.printStackTrace();
                    p(selectionKeyDevice.attachment() + "socket closed? ");
                    socketChannel.close();
                }
            } else if (selectionKeyDevice.isWritable()) {
                p(selectionKeyDevice.attachment() + "TODO: isWritable() ???????????????????????????? ");
            } else if (selectionKeyDevice.isConnectable()) {
                p(selectionKeyDevice.attachment() + "TODO: isConnectable() ????????????????????????? ");
            } else {
                p(selectionKeyDevice.attachment() + "TODO: else. ");
            }
    }
    //      
    public void handleSelectionKey(SelectionKey selectionKey) throws Exception {
            if (selectionKey.isAcceptable()) {
                //       
                clientCount++;
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                SocketChannel socketChannel = serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                Socket socket = socketChannel.socket();
                  
                System.out.println(serverSocketChannel.socket().getLocalSocketAddress());
     
                //        OP_READ  SelectionKey,         
                SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);             
                key.attach("  " + clientCount + "      [" + socket.getRemoteSocketAddress() + "]: ");
                p(key.attachment() + "\t[connected] =========================================");
                } else if (selectionKey.isReadable()) {
                    //      
                    ByteBuffer byteBuffer = ByteBuffer.allocate(100);
                    ByteBuffer byteBufferDD= ByteBuffer.allocate(100);
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
     
                    SocketChannel socketChannelDevice=(SocketChannel)map.get("/192.168.1.102").channel();
                    System.out.println(map.get("/192.168.1.102"));
                    //System.out.println(socketChannelDevice.socket().getPort());
                    try {
                        //      
                        int instruction = socketChannel.read(byteBuffer);
                        int data=socketChannelDevice.read(byteBufferDD);
                        if (instruction > 0) {
                            byteBuffer.flip();//flip()                 ,    limit   position    ,   position    0   
                            //socketChannel.write(byteBuffer);
                            socketChannelDevice.write(byteBuffer);                         
                        }
                            //        
                          
                              
                        else if (data > 0)
                        {
                            byteBuffer.flip();
                            socketChannel.write(byteBuffer);
                        } else {
                            //     ,   socketChannel
                            p(selectionKey.attachment() + "read finished. close socketChannel. ");
                            socketChannel.close();
                        }
                    } catch (Exception e) {
                        //   read    ,        ,     socketChannel
                        e.printStackTrace();
                        p(selectionKey.attachment() + "socket closed? ");
                        socketChannel.close();
                    }
                } else if (selectionKey.isWritable()) {
                    p(selectionKey.attachment() + "TODO: isWritable() ???????????????????????????? ");
                } else if (selectionKey.isConnectable()) {
                    p(selectionKey.attachment() + "TODO: isConnectable() ????????????????????????? ");
                } else {
                    p(selectionKey.attachment() + "TODO: else. ");
                }
    }
    public static void p(Object object) {
        System.out.println(object);
    }
    public static void main(String[] args) throws Exception {
        new myServer();
    }
}

좋은 웹페이지 즐겨찾기