xiangpei
2025-04-18 ccadf9480d4e6a9dcc227a2a0b1f9ae0612e36fd
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
package com.monkeylessey.websocket;
 
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.URLUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.monkeylessey.framework.utils.TokenUtil;
import com.monkeylessey.sys.domain.vo.SysUserVO;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
 
import java.util.Map;
import java.util.Objects;
 
 
/**
 * URL参数处理程序,这时候连接还是个http请求,没有升级成webSocket协议,此处SimpleChannelInboundHandler泛型使用FullHttpRequest
 *
 * @author Nanase Takeshi
 * @date 2022/5/7 15:07
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyWebSocketParamHandler extends ChannelInboundHandlerAdapter {
 
    private String secret;
 
    public NettyWebSocketParamHandler(String secret) {
        this.secret = secret;
    }
 
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof DefaultHttpRequest) {
            // 获取请求头中的身份验证令牌
            DefaultHttpRequest request = (DefaultHttpRequest) msg;
            HttpHeaders headers = request.headers();
            if (headers.size() < 1) {
                ctx.channel().close();
                return;
            }
            String token = headers.get("Sec-WebSocket-Protocol");
            // token验证
//            this.handleToken(token, ctx);
//            ctx.pipeline().remove(this);
//            // 对事件进行传播,知道完成WebSocket连接。
//            ctx.fireChannelRead(msg);
        }
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }
 
    // 处理token
    private String handleToken(String token, ChannelHandlerContext ctx) {
        if (! StringUtils.hasText(token)) {
            NettyConnect.getChannelGroup().remove(ctx.channel());
            throw new RuntimeException("非法的访问凭证");
        }
        // 获取 userId 参数
        SysUserVO currentUserInfo = null;
        try {
            currentUserInfo = TokenUtil.getCurrentUserInfoStatic(token, secret);
        } catch (JsonProcessingException e) {
            NettyConnect.getChannelGroup().remove(ctx.channel());
            throw new RuntimeException("非法的访问凭证");
        }
        if (Objects.isNull(currentUserInfo)) {
            NettyConnect.getChannelGroup().remove(ctx.channel());
            throw new RuntimeException("用户不存在");
        }
        String userId = currentUserInfo.getId();
        AttributeKey<String> userIdKey = AttributeKey.valueOf("userId");
        ctx.channel().attr(userIdKey).set(userId);
        NettyConnect.getUserChannelMap().put(userId, ctx.channel());
        return userId;
    }
 
}