gpt4 book ai didi

java - Netty:如何将查询字符串与 websocket 一起使用?

转载 作者:行者123 更新时间:2023-11-30 07:12:54 24 4
gpt4 key购买 nike

这是我的ChannelInitializer#initChannel的代码片段

    ChannelPipeline p = ch.pipeline();

p.addLast(new HttpServerCodec()
.addLast(new HttpObjectAggregator(65536))
.addLast( new LoggingHandler(LogLevel.INFO))
.addLast(new WebSocketServerProtocolHandler("/chat"))
.addLast(new TextWebSocketFrameToChatMessageDecoder())
.addLast(new UserAccessHandler())

它可以通过ws://mydomain/chat接受,现在我想解析这样的查询字符串ws://mydomain/chat?accesskey=hello >

我已经查找了WebSocketServerProtocolHandler,但我找不到如何获取查询字符串。

如何获取(或解析)查询字符串?感谢您的帮助。

最佳答案

重写方法:userEventTriggered 并处理事件 HandshakeComplete。

参见WebSocketServerProtocolHandshakeHandler

Netty 4.1

public class TextWebSocketFrameToChatMessageDecoder extends SimpleChannelInboundHandler<WebSocketFrame> {
public final static AttributeKey<Map<String,String>> RequestParams = AttributeKey.valueOf("request.params");

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof HandshakeComplete){
HandshakeComplete handshake = (HandshakeComplete)evt;

//http request header
HttpHeaders headers = handshake.requestHeaders();

//http request uri: /chat?accesskey=hello
String uri = handshake.requestUri();

//TODO: parse uri parameters to map ...
Map<String, String> params ;

//put to channel context
ctx.channel().attr(RequestParams).set(params);

}else{
ctx.fireUserEventTriggered(evt);
}
}

@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
//on message
if (frame instanceof TextWebSocketFrame) {
Map<String, String> params = ctx.channel().attr(RequestParams).get();
String accesskey = params.get("accesskey");
System.out.println( accesskey ); //hello
} else {
System.out.println( "Unsupported frame type: " + frame.getClass().getName() );
}
}
}

关于java - Netty:如何将查询字符串与 websocket 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38895443/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com