Java NIO 实现聊天

服务端

package qf.test.test07;

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;

/**
 * 2020/8/11
 * 17:54
 */
public class ChatServer {
    public static void main(String[] args) {
        ServerSocketChannel listener=null;
        try {
            //创建serverSocketChannel
            listener = ServerSocketChannel.open();
            //绑定端口号和地址
            listener.bind(new InetSocketAddress("10.0.139.119", 8888));
            //设定模式,非阻塞模式
            listener.configureBlocking(false);
            //创建选择器
            Selector selector=Selector.open();
            //注册到选择器中,并指定注册的事件
            listener.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("服务器已经启动");
            //轮询(select()阻塞方法,没有事件发送阻塞)
            while(selector.select()>0){
                //处理
                //返回所有的事件的集合
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                //遍历
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey selectionKey=iterator.next();
                    //监听事件,表示有客户端发出请求
                    if(selectionKey.isAcceptable()){
                        //创建socketChannel
                        SocketChannel socketChannel = listener.accept();

                            System.out.println(((InetSocketAddress) socketChannel.getRemoteAddress()).getAddress() + "进入了聊天室");
                            //设定非阻塞模式
                            socketChannel.configureBlocking(false);
                            //注册到选择器
                            socketChannel.register(selector, SelectionKey.OP_READ);

                        //读取键
                    }else if(selectionKey.isReadable()) {
                        //返回创建此键的通道
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        //创建缓冲区
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取数据
                        int len = 0;
                        //如果有数据
                        try {
                            while ((len = channel.read(byteBuffer)) > 0) {
                                byteBuffer.flip();
                                System.out.println(((InetSocketAddress) channel.getRemoteAddress()).getAddress() + ":" + new String(byteBuffer.array(), 0, byteBuffer.limit()));
                                byteBuffer.clear();
                            }
                            if (len == -1) {//客户端关闭了
                                System.out.println(((InetSocketAddress) channel.getRemoteAddress()).getAddress() + "退出了");
                                channel.close();
                            }
                        } catch (IOException e) {
                            System.out.println(((InetSocketAddress) channel.getRemoteAddress()).getAddress() + "异常退出了");
                            try {
                                channel.close();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                    //已经处理过的键要清除
                    iterator.remove();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                listener.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

用户端:

package qf.test.test07;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 2020/8/11
 * 18:59
 */
public class ChatClient {
    public static void main(String[] args) {
        SocketChannel socketChannel=null;
        try {
             socketChannel =SocketChannel.open(new InetSocketAddress("10.0.139.119", 8888));
            Scanner input=new Scanner(System.in);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            try {
                while(true){
                    String str=input.next();
                    byteBuffer.put(str.getBytes());
                    byteBuffer.flip();
                    socketChannel.write(byteBuffer);
                    byteBuffer.clear();
                    if(str.equals("886")){
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

注意register()方法的第二个参数。这是一个“interest集合”,意思是在通过Selector监听Channel时对什么事件感兴趣。
通道触发了一个事件意思是该事件已经就绪。所以,某个channel成功连接到另一个服务器称为“连接就绪”。一个server socket channel准备好接收新进入的连接称为“接收就绪”。一个有数据可读的通道可以说是“读就绪”。等待写数据的通道可以说是“写就绪”。
一旦调用了select()方法,并且返回值表明有一个或更多个通道就绪了,然后可以通过调用selector的selectedKeys()方法,访问“已选择键集(selected key set)”中的就绪通道
当像Selector注册Channel时,Channel.register()方法会返回一个SelectionKey 对象。这个对象代表了注册到该Selector的通道。
注意每次迭代末尾的keyIterator.remove()调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值