【2018.07.29】NIO的案例

//client端的代码
package com.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;
import java.util.Set;

public class NIOClient {
    private static int flag = 1;
    private static  int blockSize =  4096;

    private static ByteBuffer sendbuffer =  ByteBuffer.allocate(blockSize);//
    private static ByteBuffer receivebuffer = ByteBuffer.allocate(blockSize);//

    //有了这些属性之后

    private final static InetSocketAddress servereAddress = new InetSocketAddress("127.0.0.1", 7080);

    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();//打开选择器

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);//设置成非阻塞的

        socketChannel.register(selector,SelectionKey.OP_CONNECT);//事件注册好以后

        socketChannel.connect(servereAddress);
        //遍历我们的事件key
        Set<SelectionKey> selectionKeys;
        Iterator<SelectionKey> iterator;
        SelectionKey selectionKey;
        SocketChannel client;
        String receiveText;
        String sendText;
        while(true){
            selector.select();
            selectionKeys = selector.selectedKeys();//获得了所有的keys
            iterator = selectionKeys.iterator();
            while(iterator.hasNext()){//
                selectionKey  = iterator.next();//拿到selectkey
                if(selectionKey.isConnectable()){//可以连接的
                    //客户端开始发起连接。
                    System.out.println("client connect");//
                    client = (SocketChannel)selectionKey.channel();//客户端channel
                    if(client.isConnectionPending()){//客户端连接
                        client.finishConnect();//
                        System.out.println("客户端完成连接");
                        sendbuffer.clear();//清空缓存区
                        sendbuffer.put("Hello,Servet".getBytes());//
                        sendbuffer.flip();//
                        client.write(sendbuffer);
                    }
                    client.register(selector, SelectionKey.OP_READ);//
                }
                if(selectionKey.isReadable()){//服务端发送过来的数据
                    client = (SocketChannel)selectionKey.channel();
                    receivebuffer.clear();//清空全部的缓冲区
                    int count = client.read(receivebuffer);//
                    if(count>0){
                        receiveText = new String(receivebuffer.array(),0,count);
                        System.out.println("客户端接收到服务端的数据:"+receiveText);//客户端接收到服务端的text
                        client.register(selector, selectionKey.OP_WRITE);//
                    }
                }
                if(selectionKey.isWritable()){//向服务端写数据
                    sendbuffer.clear();//
                    client = (SocketChannel)selectionKey.channel();//
                    sendText = "MSG send to Server->"+flag++;
                    sendbuffer.put(sendText.getBytes());//
                    sendbuffer.flip();//
                    client.write(sendbuffer);//
                    System.out.println("客户端发送数据给客户端:"+sendText);
                    client.register(selector, selectionKey.OP_READ);
                }
                iterator.remove();
            }
            selectionKeys.clear();//每次的selectionKeys清空
        }
    }

}
//socketChannel的实现
package com.nio;

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

public class NIOServer {
    private int blockSize =  4096;
    private ByteBuffer sendbuffer =  ByteBuffer.allocate(blockSize);
    private ByteBuffer receivebuffer = ByteBuffer.allocate(blockSize);
    private static Selector selector;

    public NIOServer(int port) throws IOException{
        ServerSocketChannel serverSocketChannel =  ServerSocketChannel.open();//打开服务端channel
        serverSocketChannel.configureBlocking(false);//通道非阻塞
        ServerSocket serverSocket = serverSocketChannel.socket();//对于我们的serverScoket
        //绑定了服务端的socket
        serverSocket.bind(new InetSocketAddress(port));
        selector = Selector.open();//静态方法获取selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//注册这个事件之后
        System.out.println("Server start->"+port);//初始化工作
    }

    public void listen() throws IOException{
        while(true){
            selector.select();//轮询我们的选择器
            //获取的是我们的事件链表
            Set<SelectionKey> selectionKeys =  selector.selectedKeys();//返回的是selectionKey;
            Iterator<SelectionKey> iterator = selectionKeys.iterator();//
            while(iterator.hasNext()){
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                //业务逻辑
                handleKey(selectionKey);
            }
        }
    }

    public  void handleKey(SelectionKey selectionKey) throws IOException{
        ServerSocketChannel server = null;
        SocketChannel client = null;
        String reciveText;
        int count = 0;
        if(selectionKey.isAcceptable()){//可接受的事件的事件
            server = (ServerSocketChannel)selectionKey.channel();
            client = server.accept();//
            client.configureBlocking(false);//不阻塞
            client.register(selector,selectionKey.OP_READ);//
        }else if(selectionKey.isReadable()){//读
            client  = (SocketChannel)selectionKey.channel();//客户端的channel
            count = client.read(receivebuffer);//读到缓冲区里去
            if(count>0){
                reciveText = new String(receivebuffer.array(),0,count);//就是我们接收到客户端的数据
                System.out.println("服务端接收到客户端的信息:"+reciveText);
                client.register(selector, selectionKey.OP_WRITE);
            }
        }else if(selectionKey.isWritable()){
            //写的缓冲区清零
            sendbuffer.clear();
            client = (SocketChannel) selectionKey.channel();//
            sendbuffer.put("msg send to client".getBytes());
            sendbuffer.flip();
            client.write(sendbuffer);
            System.out.println("服务端发送数据给客户端: msg send to client");
        }
    } 
    public static void main(String[] args) throws Exception {
        int port = 7080;
        NIOServer nioServer = new NIOServer(port);
        nioServer.listen();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值