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

/**  
* 类说明  :NIO服务端的读写
* @author   郭莹棋
* @date 2018年10月19日
*/

public class NioServerGy {
public static void main(String[] args) throws IOException {
    int port = 5555;
    //获取ServerSocket信道实例
    ServerSocketChannel sc = ServerSocketChannel.open();
    //绑定信道端口
    sc.bind(new InetSocketAddress(port));
    //设置为非阻塞
    sc.configureBlocking(false);
    //获取Selector实例
    Selector s = Selector.open();
    //当前信道接受网络请求
    sc.register(s, SelectionKey.OP_ACCEPT);
    //设置标识
    int num = 0;
    //开辟一个50字节的空间出来
    ByteBuffer buffer = ByteBuffer.allocate(50);
    //获取所有信道数量
    while((num = s.select()) >= 0) {
        Set<SelectionKey> keys = s.selectedKeys();
        Iterator<SelectionKey> iterator = keys.iterator();
        while(iterator.hasNext()) {
            SelectionKey key = iterator.next();
            if(!key.isValid()) {
                key.cancel();
                continue;
            }
        if(key.isAcceptable()) {
            System.out.println("当前信道为接收请求");
            //当前信道接收请求
            ServerSocketChannel channel = (ServerSocketChannel)key.channel();
            //获取相连的客户端请求
            SocketChannel client = channel.accept();
            //设置接收数据信道为非阻塞
            client.configureBlocking(false);
            //将该信道注册到Selector上
            channel.register(s, SelectionKey.OP_READ);
            key.cancel();
            continue;
        }
        if(key.isReadable()) {
            SocketChannel channel = (SocketChannel)key.channel();
            int read = channel.read(buffer);
            String string = new String(buffer.array(),0,buffer.remaining());
            System.out.println("[client]"+string);
            buffer.clear();
            String recvMsg = "[server]"+string;
            buffer.put(recvMsg.getBytes());
            //buffer.flip();
            //channel.write(buffer);
            channel.register(s,SelectionKey.OP_WRITE );
            buffer.clear();
            key.cancel();
            continue;
            }
        if(key.isWritable()) {
            SocketChannel channel = (SocketChannel)key.channel();
            Scanner cc = new Scanner(System.in);
            String ss = cc.nextLine();
            channel.write(ByteBuffer.wrap(ss.getBytes()));
        }
        }
    }
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值