Html WebSocket 地址可以带参数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17301269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:28:32  来源:igfitidea点击:

Can WebSocket addresses carry parameters?

javascripthtmlnode.jswebsocket

提问by Jo?o Pinto Jerónimo

Is ws://myserver.com/path?param=1a valid WebSocket address ?

ws://myserver.com/path?param=1有效的 WebSocket 地址吗?

The address http://myserver.com/path?param=1(notice it's now httpand not ws) works fine with wscat, but I can't get it working on the browser.

地址http://myserver.com/path?param=1(注意它是现在http而不是ws)与 一起工作正常wscat,但我无法在浏览器上使用它。

采纳答案by kanaka

ws://myserver.com/path?param=1is a valid WebSocket URI. However, the way that your WebSocket server application can access the path and query string will differ depending on what WebSocket server framework you are using.

ws://myserver.com/path?param=1是有效的 WebSocket URI。但是,您的 WebSocket 服务器应用程序访问路径和查询字符串的方式会因您使用的 WebSocket 服务器框架而异。

If you are using the Node.js einaros/wslibrary, then in your websocket connection object will have the full path with the query string at upgradeReq.url.

如果您使用的是 Node.jseinaros/ws库,那么在您的 websocket 连接对象中将具有查询字符串的完整路径upgradeReq.url

For example this:

例如这个:

wss.on('connection', function(ws) {
    console.log("url: ", ws.upgradeReq.url);
};

will print url: /path?param=1when you connect to ws://myserver.com/path?param=1.

url: /path?param=1连接到 时将打印ws://myserver.com/path?param=1

回答by singhspk

To use with latest ws, the connection callback now has another argument - which is req.

要与最新的 ws 一起使用,连接回调现在有另一个参数 - 即 req。

wss.on("connection", (ws, req) => {
   console.log(`Conn Url ${req.url}`);
});