Netty-基于NIO实现群聊系统-逐步搭建

1、功能介绍

  • 基于NIO实现一个群聊系统,实现服务器端和客户端之间的简单通讯,非阻塞方式
  • 实现多人群聊,客户端的消息可以无阻塞的发给所有的其他用户,也能接收其它用户的消息
  • 服务器端:需要监测用户上线、下线,实现客户端消息转发功能
  • 客户端:通过通道无阻塞的发送消息给其它用户,并接收其他用户的消息

2、系统分析

在这里插入图片描述

  • **服务器端:**服务器启动并监听端口,服务器接收客户端的消息并转发,同时处理客户端上线和离线
  • **客户端:**连接服务器,发送消息,接收服务器转发的消息

3、服务器端实现

package NIO.groupchat;

import com.sun.jdi.event.StepEvent;

import javax.swing.event.ListSelectionListener;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    //定义相关属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static 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注册到selector
                            sc.register(selector,SelectionKey.OP_READ);
                            //提醒事项
                            System.out.println(sc.getRemoteAddress()+" 上线");
                        }
                        //通道发送read事件,此时通道是可读状态
                        if(key.isReadable()){
                            readData(key);
                        }
                        //删除当前key,下一次遍历直接到下一个
                        iterator.remove();
                    }
               }else{
                    System.out.println("等待...");
                }
            }   
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            //异常处理
        }
    }
    //读取客户端信息
    private void readData(SelectionKey key) {
        //读取关联的channel
        SocketChannel channel = null;
        try {
            //得到channe
            channel = (SocketChannel)key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if(count > 0){
                //把缓存区的数据存成字符串
                String msg = new String(buffer.array());
                //输出该消息
                System.out.println("FROM 客户端:"+ msg);
                //向其他客户端转发消息
                sendInfoToOtherClient(msg,channel);
            }
        }catch (IOException e){
            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ee){
                ee.printStackTrace();
            }
        }
    }
    
    //转发消息给其他客户端/的通道
    private void sendInfoToOtherClient(String msg, SocketChannel self) throws IOException{
        System.out.println("服务器转发消息中...");
        //遍历所有注册到selector的SocketChannel,排除发送消息的那个
        for(SelectionKey key : selector.keys()){
            //通过key获取对应的SockeChannel
            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();
    }
}

4、客户端实现

package 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.sql.BatchUpdateException;
import java.util.Iterator;
import java.util.Scanner;

/*客户端*/
public class GroupChatClient {
    /*定义相关属性*/
    //服务器IP
    private final String HOST = "127.0.0.1";
    //服务器端口
    private final int POST = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    //使用构造器完成初始化工作
    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接至服务器
        socketChannel = socketChannel.open(new InetSocketAddress("127.0.0.1",POST));
        //设置为非阻塞模式
        socketChannel.configureBlocking(false);
        //将channel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到用户名
        username = socketChannel.getRemoteAddress().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();
            }else{
                System.out.println("没有可用通道...");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    //主程序,进行测试
    public static void main(String[] args) throws Exception {
        //启动客户端
        GroupChatClient groupChatClient = new GroupChatClient();
        //启动一个新线程,每三秒读取从服务器发送的数据
        new Thread(){
            @Override
            public void run(){
                while(true){
                    groupChatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器
        Scanner scanner = new Scanner(System.in);

        while(scanner.hasNextLine()){
            String str = scanner.nextLine();
            groupChatClient.sendInfo(str);
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值