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 userIdKey = AttributeKey.valueOf("userId"); ctx.channel().attr(userIdKey).set(userId); NettyConnect.getUserChannelMap().put(userId, ctx.channel()); return userId; } }