Netty:如何在Websocket中使用查询字符串? [英] Netty: How to use query string with websocket?

查看:134
本文介绍了Netty:如何在Websocket中使用查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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

It can be accepted via ws://mydomain/chat, and now I want to parse query string like this ws://mydomain/chat?accesskey=hello

我查询了WebSocketServerProtocolHandler,但是找不到如何获取查询字符串.

I have looked up WebSocketServerProtocolHandler, but I couldn't find how to get query string.

如何获取(或解析)查询字符串? 谢谢你的帮助.

How can I get(or parse) query string? Thanks for your help.

推荐答案

我创建了3个新类,并将它们复制了.

I have created 3 new classes, copied them.

WebSocketServerProtocolHandler
WebSocketServerProtocolHandshakeHandler
WebSocketProtocolHandler

WebSocketServerProtocolHandler
WebSocketServerProtocolHandshakeHandler
WebSocketProtocolHandler

在WebSocketServerProtocolHandshakeHandler的副本中,添加了这些代码

And in copy of WebSocketServerProtocolHandshakeHandler, added these code

if(!req.getUri().matches(websocketPath)){
    ctx.fireChannelRead(msg);
    return;
}

String [] splittedUri = req.getUri().split("\\?");
HashMap<String, String> params = new HashMap<String, String>();

if(splittedUri.length > 1){
    String queryString = splittedUri[1];
    for(String param : queryString.split("&")){
        String [] keyValue = param.split("=");
        if(keyValue != null && keyValue.length >= 2){
            logger.trace("key = {}, value = {}", keyValue[0], keyValue[1]);
            params.put(keyValue[0], keyValue[1]);
        }
    }
}

ctx.channel().attr(AttrKeys.getInstance().params()).set(params);

现在,我可以支持多个uri并很好地使用查询字符串. 我认为有人会需要这个答案.

Now I can accpet multiple uri and use query string well. I think somebody will need this answer.

这篇关于Netty:如何在Websocket中使用查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆