websocket创建时传参数
调用小程序的websocket,但是不论是data还是header都无法传参数,请官方给出正确的使用方式!
代码:
wx.connectSocket({
url: ‘ws://host/socket’,
data: {
userId: 1
}
,
header: {
‘content-type’: ‘application/json’,
‘st’: ‘TEST’
},
success: function() {
console.log(arguments);
app.alert(1, ‘链接成功’);
}
});
调试结果:
1 回复
链接改成这样:ws://host/socket?token=xxxx
如果服务端用的是netty请参考下面的代码:
/**
* 仅仅在第一次请求的时候被调用一次
*
* [@param](/user/param) ctx
* [@param](/user/param) req
* [@throws](/user/throws) Exception
*/
private void handleHttpRequest(ChannelHandlerContext ctx,
FullHttpRequest req) throws Exception {
// 如果HTTP解码失败,返回HHTP异常
if (!req.getDecoderResult().isSuccess()
|| (!"websocket".equals(req.headers().get("Upgrade")))) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
HttpResponseStatus.BAD_REQUEST));
return;
}
//Token校验
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(req.getUri());
Map<String, List<String>> params = queryStringDecoder.parameters();
if (params.containsKey("token")) {
String token = params.get("token").get(0);
if (redisService.validToken(token)) {
logger.info("websocket链接校验:{}通过", token);
// 构造握手响应返回,本机测试
try {
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
"wss://" + req.headers().get(HttpHeaders.Names.HOST), null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
handshaker.handshake(ctx.channel(), req);
}
} catch (Exception e) {
e.printStackTrace();
logger.info("websocket握手好像失败了");
}
} else {
logger.info("websocket链接校验:{}未通过", token);
//校验不通过
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
HttpResponseStatus.BAD_REQUEST));
}
} else {
logger.info("websocket链接校验未获取到token。 channelName:{}", ctx.name());
}
}