JAVA NIO实现

服务器端:

package NIO;

import org.aspectj.lang.annotation.Pointcut;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
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;

/**
 * Created by z84102272 on 2018/8/9.
 */
public class NIOServer {

    //通道管理器
    private Selector selector;

    /**
     * 获得一个ServerSocket通道,并对该通道做一些初始化的工作
     * @param port 绑定的端口号
     * @throws IOException
     */
    public void initServer(int port) throws IOException {
        // 获得一个ServerSocket通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 设置通道为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 将该通道对应的ServerSocket绑定到port端口
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        // 获得一个通道管理器
        this.selector = Selector.open();
        //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,
        //当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    /**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     */
    @SuppressWarnings("unchecked")
    public void listen() throws IOException{
        System.out.println("server init success...");
        //轮询访问selector
        while (true){
            //当注册的事件到达时,方法返回;否则该方法会一直阻塞
            selector.select();
            //获得selector中选中的项的迭代器,选中的项为注册的事件
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()){
                SelectionKey key = (SelectionKey) ite.next();
                //删除已选择key,防止重复处理
                ite.remove();
                //客户端请求连接事件
                if (key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    //获得和客户端连接的通道
                    SocketChannel channel = server.accept();
                    //设置为非阻塞
                    channel.configureBlocking(false);

                    //给客户端发送消息
                    channel.write(ByteBuffer.wrap(new String("向客户端发送一条消息").getBytes()));
                    //在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。
                    channel.register(this.selector,SelectionKey.OP_READ);

                }else if (key.isReadable()){
                    read(key);
                }
            }
        }
    }

    /**
     * 处理客户端发来的信息的事件
     */
    public void read(SelectionKey key) throws IOException{
        //服务器可读消息:得到事件发生的socket通道
        SocketChannel channel = (SocketChannel)key.channel();
        //创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(10);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("服务器端收到信息:" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer); //将消息回传给客户端
    }

    /**
     * 启动服务端测试
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.initServer(8000);
        server.listen();
    }
    
}

  客户端:

package 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.util.Iterator;

/**
 * Created by z84102272 on 2018/8/9.
 */
public class NIOClient {
    //通道管理器
    private Selector selector;

    /**
     * 获得一个Socket通道,并对该通道做一些初始化的工作
     * @param ip 连接的服务器的ip
     * @param port 连接的服务器的端口号
     * @throws IOException
     */
    public void initClient(String ip,int port) throws IOException{
        //获得一个socket通道
        SocketChannel channel = SocketChannel.open();
        //设置通道为非阻塞
        channel.configureBlocking(false);
        //获得一个通道管理器
        this.selector = Selector.open();
        // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调
        //用channel.finishConnect();才能完成连接
        channel.connect(new InetSocketAddress(ip,port));
        //将通道管理器与该通道绑定,并注册事件
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    /**
     * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public void listen() throws IOException{
        //轮询访问selector
        while(true){
            selector.select();
            //获得selector中选中的迭代器
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()){
                SelectionKey key = (SelectionKey) ite.next();
                ite.remove();
                //连接事件发生
                if (key.isConnectable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    //如果正在连接,则完成连接
                    if (channel.isConnectionPending()){
                        channel.finishConnect();
                    }
                    //设置非阻塞
                    channel.configureBlocking(false);

                    channel.write(ByteBuffer.wrap(new String("向服务端发生消息").getBytes()));
                    //在和服务端连接成功之后,为了可以接受到服务器端的信息,需要给通道设置读的权限
                    channel.register(selector,SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    read(key);
                }
            }
        }
    }

    /**
     * 处理读取服务器发的信息
     */
    public void read(SelectionKey key) throws IOException{
        //服务器可读消息:得到事件发生的socket通道
        SocketChannel channel = (SocketChannel)key.channel();
        //创建读取的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(10);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("客户端收到信息:" + msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer); //将消息回传给客户端
    }

    /**
     * 启动客户端测试
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("localhost",8000);
        client.listen();
    }




}

  

posted @ 2018-07-24 20:06  爱生活1  阅读(166)  评论(0编辑  收藏  举报