[Netty] 基于NIO的简单群聊系统

介绍

基于NIO的后端群聊系统,实现的功能有

  1. 监听客户端的上线和下线、
  2. 监听客户端的消息的发送

代码

服务端

package com.gxd.nio.groupchat;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.omg.CORBA.IRObject;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Iterator;

public class GroupChatServer {
    // 定义属性
    private Selector selector;

    private ServerSocketChannel listenChannel;
    // 定义端口号
    private static final int PORT = 7999;

    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();

            // 获取监听器
            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) {
                    // 如果有事件就处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    if (iterator.hasNext()) {
                        // 获取到selectionKey
                        SelectionKey key = iterator.next();
                        // 监听到accept
                        if (key.isAcceptable()) {
                            // 获取通道
                            SocketChannel channel = listenChannel.accept();
                            // 设置为非阻塞
                            channel.configureBlocking(false);
                            // 将通道注册到Selector
                            channel.register(selector, SelectionKey.OP_READ);
                            // 提示
                            System.out.println(channel.getRemoteAddress() + "上线了");
                        }
                        // 通道发生read事件
                        if (key.isReadable()) {
                            readHandler(key);
                        }
                        // 从集合中删除当前key,防止重复操作
                        iterator.remove();
                    }
                } else {
                    System.out.println("wait...");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 读取客户端消息
     *
     * @param key
     */
    private void readHandler(SelectionKey key) {
        // 定义一个SocketChannel
        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("获得消息" + msg);
                // 向其他客户端转发消息
                SendInfoToOthers(msg, channel);
            }


        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + "已经下线...");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    /**
     * 转发消息给其他客户端
     *
     * @param msg
     * @param self
     */
    private void SendInfoToOthers(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息...");
        // 遍历所有组册道Selector上的SocketChannel,并排除自己
        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.gxd.nio.groupchat;

import jdk.internal.org.objectweb.asm.TypeReference;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.security.cert.TrustAnchor;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {

    // 定义相关属性
    // 服务器IP
    private final String HOST = "127.0.0.1";
    // 服务器端口
    private final int PORT = 7999;

    private Selector selector;

    private SocketChannel socketChannel;

    private String userName;

    private GroupChatClient() throws IOException {
        selector = Selector.open();

        socketChannel = socketChannel.open(new InetSocketAddress(HOST, PORT));
        // 设置非阻塞
        socketChannel.configureBlocking(false);

        socketChannel.register(selector, SelectionKey.OP_READ);
        // 得到username
        userName = socketChannel.getLocalAddress().toString().substring(1);
    }

    /**
     * 向服务器发送消息
     */
    public void sendInfo(String info) {
        info = userName + ":说:" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取从服务器发送的消息
     */
    private 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 channel = (SocketChannel) key.channel();
                        // 得到一个buffer
                        ByteBuffer allocate = ByteBuffer.allocate(1024);
                        // 读取
                        channel.read(allocate);
                        String msg = new String(allocate.array());
                        // 输出
                        System.out.println(msg);
                        iterator.remove();
                    } else {
                        System.out.println("没有可用的通道");
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        // 启动客户端
        GroupChatClient chatClient = new GroupChatClient();
        // 启动线程
        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);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值