首页 > 其他 > 详细

NIO实例

时间:2015-10-07 00:57:16      阅读:239      评论:0      收藏:0      [点我收藏+]

服务端程序

package main;

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

/**
 * @author doggy
 *         Created on 15-10-6.
 */
public class Server {
    public static void main(String[] args){
        try{
            //open a selector
            Selector selector = Selector.open();
            //create a serversocketchannel and init
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.socket().bind(new InetSocketAddress(18530));
            //set it to non blocking,only in this way you can register it to a selector
            ssc.configureBlocking(false);
            //register to OP_ACCEPT,means when accpt this channel would add to selectedChannels
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            while(true){
                //blocked if no event coming
                selector.select();
                //get active channel
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> ite = keys.iterator();
                while(ite.hasNext()){
                    try{
                        SelectionKey key = ite.next();
                        //for OP_ACCEPT
                        if(key.isAcceptable()){
                            ServerSocketChannel sscl = (ServerSocketChannel)key.channel();
                            SocketChannel sc = sscl.accept();
                            sc.configureBlocking(false);
                            sc.register(selector,SelectionKey.OP_READ);
                            System.out.println("connected");
                        //for OP_READ
                        }else if(key.isReadable()){
                            System.out.println("begin read");
                            //get channel
                            SocketChannel sc = (SocketChannel)key.channel();
                            ByteBuffer bb = ByteBuffer.allocate(64);
                            //deal with pipe diconnected
                            if(sc.read(bb) < 0){
                                sc.close();
                                //cancel for register and remove it from selectedKeys
                                key.cancel();
                                continue;
                            }
                            int pos = bb.position();
                            bb.flip();
                            byte[] b = new byte[64];
                            bb.get(b,0,pos);
                            String s = new String(b);
                            System.out.println(s);
                            s = "hello "+s;
                            //attach message to key
                            key.attach(s);
                            //registe a write event
                            key.interestOps(SelectionKey.OP_WRITE);
                            System.out.println("end read");
                        //for OP_WRITE
                        }else if(key.isWritable()){
                            System.out.println("begin write");
                            SocketChannel sc = (SocketChannel)key.channel();
                            ByteBuffer bb;
                            //get attach message
                            String s = (String)key.attachment();
                            bb = ByteBuffer.wrap(s.getBytes());
                            sc.write(bb);
                            key.interestOps(SelectionKey.OP_READ);
                            System.out.println("end write");
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    } finally{
                        //remove it from selectedKey anyway
                        ite.remove();
                    }
                }
            }
        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}

 客户端程序

package main;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author doggy
 *         Created on 15-10-6.
 */
public class Client {
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("127.0.0.1",18530);
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        Scanner in = new Scanner(System.in);
        while(true){
            String s = in.nextLine();
            if(s.toLowerCase().equals("eof")){
                socket.close();
                break;
            }
            os.write(s.getBytes());
            byte[] b = new byte[128];
            is.read(b);
            System.out.println(new String(b));
        }
    }
}

 

NIO实例

原文:http://www.cnblogs.com/fcat/p/4858106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!