zhitong.yu
2024-10-11 4f58a93c95ff123d51adcb8fa2e521333e8ab022
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package com.hxzk.util.Netty;
 
 
import com.hxzk.util.TokenUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.beans.factory.annotation.Autowired;
 
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
 
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
 
 
    @Resource
    TokenUtil tokenUtil;
    //定义一个channle 组,管理所有的channel
    //GlobalEventExecutor.INSTANCE) 是全局的事件执行器,是一个单例
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
 
    //handlerAdded 表示连接建立,一旦连接,第一个被执行
    //将当前channel 加入到  channelGroup
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
 
        Channel channel = ctx.channel();
        String token = ctx.channel().attr(AttributeKey.<String>valueOf("token")).get();
        System.out.println(token+"获取token");
        System.out.println("解析token");
//        if (token.equals("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aW1lU3RhbXAiOjE3MjM3NzIwMzAxMTEsInVzZXJJZCI6IlwiZmdoZ2Y4ZmdqOGZnZjIza3Nkc2Q0c3I1NzgxZ2hqOGxcIiJ9.W0zHbIzX9RFADWDRpNY_hj0NSq34psi52BvA7ay7DO0")){
            //将该客户加入聊天的信息推送给其它在线的客户端
        /*
        该方法会将 channelGroup 中所有的channel 遍历,并发送 消息,我们不需要自己遍历
         */
            channelGroup.add(channel);
//        }else{
//            channel.writeAndFlush("Invalid token. Disconnecting...\n").addListener(ChannelFutureListener.CLOSE);
//            return;
//        }
 
    }
 
 
    //表示channel 处于活动状态, 提示 xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = insocket.getAddress().getHostAddress();
        int port = insocket.getPort();
 
 
        String s3 = "-----" + ip + ":" + port + ":连接了";
        System.out.println(s3);
 
    }
 
    //表示channel 处于不活动状态, 提示 xx离线了
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = insocket.getAddress().getHostAddress();
        int port = insocket.getPort();
        String s5 = "-----" + ip + ":" + port + ":断开连接-------------------------------------";
        System.out.println(s5);
 
 
    }
 
    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
 
        //获取到当前channel
        Channel channel = ctx.channel();
        //这时我们遍历channelGroup, 根据不同的情况,回送不同的消息
 
        channelGroup.forEach(ch -> {
            if (channel != ch) { //不是当前的channel,转发消息
                ch.writeAndFlush("[客户]" + channel.remoteAddress() + " 发送了消息" + msg + "\n");
            } else {//回显自己发送的消息给自己
                ch.writeAndFlush("[自己]发送了消息" + msg + "\n");
            }
        });
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
 
    }
 
    /**
     * 获取某个上线的设备对象
     */
    public static Channel get_chanel(String ip) {
        Channel channel = null;
        Iterator<Channel> it = GroupChatServerHandler.channelGroup.iterator();
        while (it.hasNext()) {
            Channel channel1 = it.next();
            InetSocketAddress insocket = (InetSocketAddress) channel1.remoteAddress();
            String ip1 = insocket.getAddress().getHostAddress();
            if (ip1.equals(ip)) {
                channel = channel1;
                break;
            }
        }
        return channel;
    }
 
}