欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现NIO聊天室的示例代码(群聊+私聊)

程序员文章站 2022-03-17 14:35:09
功能介绍功能:群聊+私发+上线提醒+下线提醒+查询在线用户文件utils需要用maven导入下面两个包 org...

功能介绍

功能:群聊+私发+上线提醒+下线提醒+查询在线用户

Java实现NIO聊天室的示例代码(群聊+私聊)

Java实现NIO聊天室的示例代码(群聊+私聊)

Java实现NIO聊天室的示例代码(群聊+私聊)

Java实现NIO聊天室的示例代码(群聊+私聊)

文件

utils

需要用maven导入下面两个包

 <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <version>1.16.18</version>
        </dependency>
        <dependency>
            <groupid>ch.qos.logback</groupid>
            <artifactid>logback-classic</artifactid>
            <version>1.2.3</version>
        </dependency>
package moremorechat_nio;

import lombok.extern.slf4j.slf4j;

import java.io.*;

/**
 * @author mazouri
 * @create 2021-05-09 22:26
 */
@slf4j
public class utils {
    /**
     * 将二进制数据转为对象
     *
     * @param buf
     * @return
     * @throws ioexception
     * @throws classnotfoundexception
     */
    public static message decode(byte[] buf) throws ioexception, classnotfoundexception {
        bytearrayinputstream bais = new bytearrayinputstream(buf);
        objectinputstream ois = new objectinputstream(bais);
        return (message) ois.readobject();
    }

    /**
     * 将对象转为二进制数据
     *
     * @param message
     * @return
     */
    public static byte[] encode(message message) throws ioexception {
        bytearrayoutputstream baos = new bytearrayoutputstream();
        objectoutputstream oos = new objectoutputstream(baos);
        oos.writeobject(message);
        oos.flush();
        return baos.tobytearray();
    }
}

finalvalue

package moremorechat_nio;
/**
 * @author mazouri
 * @create 2021-05-05 21:00
 */
public final class finalvalue {
    /**
     * 系统消息
     */
    public static final int msg_system = 0;
    /**
     * 群发消息
     */
    public static final int msg_group = 1;
    /**
     * 私发消息
     */
    public static final int msg_private = 2;
    /**
     * 客户端请求在线人员
     */
    public static final int msg_online = 3;
    /**
     * 客户端将用户名称发送给服务端
     */
    public static final int msg_name = 4;
}

message

package moremorechat_nio;

import java.io.serializable;

/**
 * @author mazouri
 * @create 2021-05-05 21:00
 */
public class message implements serializable {
    public int type;
    public string message;

    public message() {
    }

    public message(string message) {
        this.message = message;
    }

    public message(int type, string message) {
        this.type = type;
        this.message = message;
    }

    @override
    public string tostring() {
        return "message{" +
                "type=" + type +
                ", message='" + message + '\'' +
                '}';
    }
}

nioserver

package moremorechat_nio;

import lombok.extern.slf4j.slf4j;

import java.io.*;
import java.net.inetsocketaddress;
import java.nio.bytebuffer;
import java.nio.channels.*;
import java.util.arraylist;
import java.util.iterator;
import java.util.set;
import java.util.concurrent.atomic.atomicboolean;
import java.util.stream.collectors;

import static moremorechat_nio.finalvalue.*;

/**
 * ctrl+f12 方法
 * ctrl+alt+左键
 * @author mazouri
 * @create 2021-05-09 19:24
 */
@slf4j
public class nioserver {
    private selector selector;
    private serversocketchannel ssc;

    public nioserver() {
        try {
            // 创建 selector, 管理多个 channel
            selector = selector.open();
            //打开serversocketchannel,用于监听客户端的连接,它是所有客户端连接的父通道
            ssc = serversocketchannel.open();
            ssc.bind(new inetsocketaddress(8888));
            //设置连接为非堵塞模式
            ssc.configureblocking(false);
            // 2. 建立 selector 和 channel 的联系(注册)
            // selectionkey 就是将来事件发生后,通过它可以知道事件和哪个channel的事件
            //将serversocketchannel注册到reactor线程的多路复用器selector上,监听accept事件
            ssc.register(selector, selectionkey.op_accept);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    public static void main(string[] args) {
        nioserver server = new nioserver();
        log.debug("server启动完成,等待用户连接...");
        try {
            server.listen();
        } catch (exception e) {
            log.debug("发生了一些问题");
        }
    }

    /**
     * 监听用户的连接
     *
     * @throws exception
     */
    private void listen() throws exception {
        while (true) {
            // select 方法, 没有事件发生,线程阻塞,有事件,线程才会恢复运行, 通过selector的select()方法可以选择已经准备就绪的通道 (这些通道包含你感兴趣的的事件)
            //通过selector的select()方法可以选择已经准备就绪的通道 (这些通道包含你感兴趣的的事件)
            // select 在事件未处理时,它不会阻塞, 事件发生后要么处理,要么取消,不能置之不理
            selector.select();
            // 处理事件, selectedkeys 内部包含了所有发生的事件
            iterator<selectionkey> iterator = selector.selectedkeys().iterator();
            while (iterator.hasnext()) {
                selectionkey key = iterator.next();
                // 处理key 时,要从 selectedkeys 集合中删除,否则下次处理就会有问题
                iterator.remove();
                // 区分事件类型
                if (key.isacceptable()) {
                    serversocketchannel channel = (serversocketchannel) key.channel();
                    socketchannel sc = channel.accept();
                    sc.configureblocking(false);
                    sc.register(selector, selectionkey.op_read);
                } else if (key.isreadable()) {
                    dealreadevent(key);
                }
            }
        }
    }

    /**
     * 处理读事件
     *
     * @param key
     */
    private void dealreadevent(selectionkey key) {
        socketchannel channel = null;
        try {
            channel = (socketchannel) key.channel();
            bytebuffer buffer = bytebuffer.allocate(1024);
            int read = channel.read(buffer);
            // 如果是正常断开,read 的方法的返回值是 -1
            if (read == -1) {
                //cancel 会取消注册在 selector 上的 channel,并从 keys 集合中删除 key 后续不会再监听事件
                key.cancel();
            } else {
                buffer.flip();
                message msg = utils.decode(buffer.array());
                log.debug(msg.tostring());
                dealmessage(msg, key, channel);
            }
        } catch (ioexception | classnotfoundexception e) {
            system.out.println((key.attachment() == null ? "匿名用户" : key.attachment()) + " 离线了..");
            dealmessage(new message(msg_system, key.attachment() + " 离线了.."), key, channel);
            //取消注册
            key.cancel();
            //关闭通道
            try {
                channel.close();
            } catch (ioexception ioexception) {
                ioexception.printstacktrace();
            }
        }
    }

    /**
     * 处理各种消息,并发送给客户端
     *
     * @param msg
     * @param key
     * @param channel
     */
    private void dealmessage(message msg, selectionkey key, socketchannel channel) {
        switch (msg.type) {
            case msg_name:
                key.attach(msg.message);
                log.debug("用户{}已上线", msg.message);
                getconnectedchannel(channel).foreach(selectionkey -> {
                    socketchannel sc = (socketchannel) selectionkey.channel();
                    sendmsgtoclient(new message("收到一条系统消息: " + msg.message + "已上线"), sc);
                });
                break;
            case msg_group:
                getconnectedchannel(channel).foreach(selectionkey -> {
                    socketchannel sc = (socketchannel) selectionkey.channel();
                    sendmsgtoclient(new message(key.attachment() + "给大家发送了一条消息: " + msg.message), sc);
                });
                break;
            case msg_private:
                string[] s = msg.message.split("_");
                atomicboolean flag = new atomicboolean(false);
                getconnectedchannel(channel).stream().filter(sk -> s[0].equals(sk.attachment())).foreach(selectionkey -> {
                    socketchannel sc = (socketchannel) selectionkey.channel();
                    sendmsgtoclient(new message(key.attachment() + "给你发送了一条消息: " + s[1]), sc);
                    flag.set(true);
                });
                if (!flag.get()){
                    sendmsgtoclient(new message(s[1]+"用户不存在,请重新输入!!!"), channel);
                }

                break;
            case msg_online:
                arraylist<string> onlinelist = new arraylist<>();
                onlinelist.add((string) key.attachment());
                getconnectedchannel(channel).foreach(selectionkey -> onlinelist.add((string) selectionkey.attachment()));
                sendmsgtoclient(new message(onlinelist.tostring()), channel);
                break;
            case msg_system:
                getconnectedchannel(channel).foreach(selectionkey -> {
                    socketchannel sc = (socketchannel) selectionkey.channel();
                    sendmsgtoclient(new message("收到一条系统消息: " + msg.message), sc);
                });
                break;
            default:
                break;
        }
    }

    /**
     * 发送消息给客户端
     *
     * @param msg
     * @param sc
     */
    private void sendmsgtoclient(message msg, socketchannel sc) {
        try {
            byte[] bytes = utils.encode(msg);
            sc.write(bytebuffer.wrap(bytes));
        } catch (ioexception e) {
            log.debug("sendmsgtoclient出现了一些问题");
        }
    }

    /**
     * 获取所有channel,除去调用者
     *
     * @param channel
     * @return
     */
    private set<selectionkey> getconnectedchannel(socketchannel channel) {
        return selector.keys().stream()
                .filter(item -> item.channel() instanceof socketchannel && item.channel().isopen() && item.channel() != channel)
                .collect(collectors.toset());
    }
}

nioclient

package moremorechat_nio;

import lombok.extern.slf4j.slf4j;

import java.io.*;
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.scanner;

import static moremorechat_nio.finalvalue.*;

/**
 * @author mazouri
 * @create 2021-04-29 12:02
 */
@slf4j
public class nioclient {
    private selector selector;
    private socketchannel socketchannel;
    private string username;
    private static scanner input;

    public nioclient() throws ioexception {
        selector = selector.open();
        socketchannel = socketchannel.open(new inetsocketaddress("127.0.0.1", 8888));
        socketchannel.configureblocking(false);
        socketchannel.register(selector, selectionkey.op_read);
        log.debug("client启动完成......");
        log.debug("请输入你的名字完成注册");
        input = new scanner(system.in);
        username = input.next();
        log.debug("欢迎{}来到聊天系统", username);
    }

    public static void main(string[] args) throws ioexception {
        system.out.println("tips: \n1. 直接发送消息会发给当前的所有用户 \n2. @用户名:消息  会私发给你要发送的用户 \n3. 输入  查询在线用户  会显示当前的在线用户");
        nioclient client = new nioclient();

        //启动一个子线程接受服务器发送过来的消息
        new thread(() -> {
            try {
                client.acceptmessagefromserver();
            } catch (exception e) {
                e.printstacktrace();
            }
        }, "receiveclientthread").start();

        //调用sendmessagetoserver,发送消息到服务端
        client.sendmessagetoserver();
    }

    /**
     * 将消息发送到服务端
     *
     * @throws ioexception
     */
    private void sendmessagetoserver() throws ioexception {
        //先把用户名发给客户端
        message message = new message(msg_name, username);
        byte[] bytes = utils.encode(message);

        socketchannel.write(bytebuffer.wrap(bytes));
        while (input.hasnextline()) {
            string msgstr = input.next();

            message msg;
            boolean isprivate = msgstr.startswith("@");
            if (isprivate) {
                int idx = msgstr.indexof(":");
                string targetname = msgstr.substring(1, idx);
                msgstr = msgstr.substring(idx + 1);
                msg = new message(msg_private, targetname + "_" + msgstr);
            } else if ("查询在线用户".equals(msgstr)) {
                msg = new message(msg_online, "请求在线人数");
            } else {
                msg = new message(msg_group, msgstr);
            }

            byte[] bytes1 = utils.encode(msg);
            socketchannel.write(bytebuffer.wrap(bytes1));
        }
    }

    /**
     * 接受从服务器发送过来的消息
     */
    private void acceptmessagefromserver() throws exception {
        while (selector.select() > 0) {
            iterator<selectionkey> iterator = selector.selectedkeys().iterator();
            while (iterator.hasnext()) {
                selectionkey key = iterator.next();
                iterator.remove();
                if (key.isreadable()) {
                    socketchannel sc = (socketchannel) key.channel();
                    bytebuffer buffer = bytebuffer.allocate(1024);
                    sc.read(buffer);
                    message message = utils.decode(buffer.array());
                    log.debug(string.valueof(message.message));
                }
            }
        }
    }
}

到此这篇关于java实现nio聊天室的示例代码(群聊+私聊)的文章就介绍到这了,更多相关java nio聊天室内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!