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

Java基于NIO实现群聊系统

程序员文章站 2022-03-15 19:54:26
本文实例为大家分享了java基于nio实现群聊系统的具体代码,供大家参考,具体内容如下实例要求:1.编写一个 nio 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)2.实现多人群聊3.服务...

本文实例为大家分享了java基于nio实现群聊系统的具体代码,供大家参考,具体内容如下

实例要求:

1.编写一个 nio 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)

2.实现多人群聊

3.服务器端:可以监测用户上线,离线,并实现消息转发功能

4.客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)

5.目的:进一步理解 nio 非阻塞网络编程机制

6.示意图分析和代码

Java基于NIO实现群聊系统

// 服务端:

package com.atguigu.nio.groupchat;

import java.io.ioexception;
import java.net.inetsocketaddress;
import java.nio.bytebuffer;
import java.nio.channels.channel;
import java.nio.channels.selectionkey;
import java.nio.channels.selector;
import java.nio.channels.serversocketchannel;
import java.nio.channels.socketchannel;
import java.util.iterator;

public class groupchatserver {

    //定义属性
    private selector selector;
    private serversocketchannel listenchannel;

    private static final int port = 6667;

    //构造器
    //初始化工作
    public groupchatserver() {
        try {
            //得到选择器
            selector = selector.open();
            //serversocketchannel
            listenchannel = serversocketchannel.open();
            //绑定端口
            listenchannel.socket().bind(new inetsocketaddress(port));
            //设置非阻塞模式
            listenchannel.configureblocking(false);
            //将该 listenchannel 注册到 selector
            listenchannel.register(selector, selectionkey.op_accept);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }

    public void listen() {
        try {
            //循环处理
            while (true) {
                int count = selector.select();
                if (count > 0) { //有事件处理
                    // 遍历得到 selectionkey 集合
                    iterator<selectionkey> iterator = selector.selectedkeys().iterator();
                    while (iterator.hasnext()) {
                        //取出 selectionkey
                        selectionkey key = iterator.next();
                        //监听到 accept
                        if (key.isacceptable()) {
                            socketchannel sc = listenchannel.accept();
                            sc.configureblocking(false);
                            //将该 sc 注册到 seletor
                            sc.register(selector, selectionkey.op_read);
                            //提示
                            system.out.println(sc.getremoteaddress() + " 上线 ");
                        }
                        if (key.isreadable()) {//通道发送read事件,即通道是可读的状态
                            // 处理读(专门写方法..)
                            readdata(key);
                        }
                        //当前的 key 删除,防止重复处理
                        iterator.remove();
                    }
                } else {
                    system.out.println("等待....");
                }
            }
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            //发生异常处理....
        }
    }

    //读取客户端消息
    public void readdata(selectionkey key) {
        socketchannel channel = null;
        try {
            //得到 channel
            channel = (socketchannel) key.channel();
            //创建 buffer
            bytebuffer buffer = bytebuffer.allocate(1024);
            int count = channel.read(buffer);
            //根据 count 的值做处理
            if (count > 0) {
                //把缓存区的数据转成字符串
                string msg = new string(buffer.array());
                //输出该消息
                system.out.println("form客户端:" + msg);
                //向其它的客户端转发消息(去掉自己),专门写一个方法来处理
                sendinfotootherclients(msg, channel);
            }
        } catch (ioexception e) {
            try {
                system.out.println(channel.getremoteaddress() + "离线了..");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (ioexception e2) {
                e2.printstacktrace();
            }
        }
    }

    //转发消息给其它客户(通道)
    private void sendinfotootherclients(string msg, socketchannel self) throws ioexception {

        system.out.println("服务器转发消息中...");
        //遍历所有注册到 selector 上的 socketchannel,并排除 self
        for (selectionkey key : selector.keys()) {
            //通过 key 取出对应的 socketchannel
            channel targetchannel = key.channel();
            //排除自己
            if (targetchannel instanceof socketchannel && targetchannel != self) {
                //转型
                socketchannel dest = (socketchannel) targetchannel;
                //将 msg 存储到 buffer
                bytebuffer buffer = bytebuffer.wrap(msg.getbytes());
                //将 buffer 的数据写入通道
                dest.write(buffer);
            }
        }
    }

    public static void main(string[] args) {
        //创建服务器对象
        groupchatserver groupchatserver = new groupchatserver();
        groupchatserver.listen();
    }
}

// 客户端:

package com.atguigu.nio.groupchat;

~~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.scanner;
public class groupchatclient {
    //定义相关的属性
    private final string host = "127.0.0.1";//服务器的ip
    private final int port = 6667;//服务器端口
    private selector selector;
    private socketchannel socketchannel;
    private string username;
    //构造器,完成初始化工作
    public groupchatclient() throws ioexception {
        
        selector = selector.open();
        //连接服务器
        socketchannel = socketchannel.open(new inetsocketaddress(host, port));
        //设置非阻塞
        socketchannel.configureblocking(false);
        //将 channel 注册到selector
        socketchannel.register(selector, selectionkey.op_read);
        //得到 username
        username = socketchannel.getlocaladdress().tostring().substring(1);
        system.out.println(username + " is ok...");
    }
    //向服务器发送消息
    public void sendinfo(string info) {
        info = username + " 说:" + info;
        try {
            socketchannel.write(bytebuffer.wrap(info.getbytes()));
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
    //读取从服务器端回复的消息
    public void readinfo() {
        try {
            int readchannels = selector.select();
            if (readchannels > 0) {//有可以用的通道
                iterator<selectionkey> iterator = selector.selectedkeys().iterator();
                while (iterator.hasnext()) {
                    selectionkey key = iterator.next();
                    if (key.isreadable()) {
                        //得到相关的通道
                        socketchannel sc = (socketchannel) key.channel();
                        //得到一个 buffer
                        bytebuffer buffer = bytebuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        string msg = new string(buffer.array());
                        system.out.println(msg.trim());
                    }
                }
                iterator.remove(); //删除当前的 selectionkey,防止重复操作
            } else {
                //system.out.println("没有可以用的通道...");
            }
        } catch (exception e) {
            e.printstacktrace();
        }
    }
    public static void main(string[] args) throws exception {
        //启动我们客户端
        groupchatclient chatclient = new groupchatclient();
        //启动一个线程,每个 3 秒,读取从服务器发送数据
        new thread() {
            public void run() {
                while (true) {
                    chatclient.readinfo();
                    try {
                        thread.currentthread().sleep(3000);
                    } catch (interruptedexception e) {
                        e.printstacktrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器端
        scanner scanner = new scanner(system.in);
        while (scanner.hasnextline()) {
            string s = scanner.nextline();
            chatclient.sendinfo(s);
        }
    }
}

运行结果

Java基于NIO实现群聊系统

Java基于NIO实现群聊系统

Java基于NIO实现群聊系统

Java基于NIO实现群聊系统

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。