问题描述
限时送ChatGPT账号..是否有适用于 node.js 的 websocket 框架,我可以在其中指定 websockets 服务器路径中的通配符?
is there a websocket framework for node.js where I can specifiy a wildcard in the websockets server path?
我想使用这样的路径
/some/:id
在这种情况下,应该能够连接到与上述字符串匹配的 url.服务器可以访问 id 并且可以为不同的频道提供服务.
In this case one should be able to connect to the urls that match the above string. The server has access to the id and can serve different channels.
例如:当使用模块 'ws' 时,可以为 http 服务器上的一个特定路径设置一个 websocket 服务器:
For example: When using the module 'ws' one can setup a websocket server for one specific path on a http server:
new WebSocket.Server({server: someHttpServer, path:'/some/path'})
从这里开始,您可以使用 WebSocket 对象从浏览器连接到您的 websocket 服务器:
From here on you can connect to your websocket server from the browser with a WebSocket Object:
let client = new WebSocket('ws://.../some/path')
我正在寻找的是这样的
new WebSocket.Server({server: someHttpServer, path:'/some/:id'})
这样我就可以连接到 websocket 并提供一个预定义的 id
so that I can connect to the websocket an deliver a predefined id
let clientA = new WebSocket('ws://.../some/idA')
let clientB = new WebSocket('ws://.../some/idB')
推荐答案
由于没有答案,我假设实际上没有答案.
Since there are no answers I assume there actually is none.
我发现 Websocket.Server 类中的 shouldHandle 方法负责决定请求的 websocket 路径.这很容易被覆盖,如下所示:
I found out the the shouldHandle method in the Websocket.Server class is repsonsible for deciding about the requested websocket path. This can easily be overwritten like so:
WebSocket.Server.prototype.shouldHandle = function shouldHandle(req) {
// Add your own logic and return `true` or `false` accordingly.
};
为了做我想做的事情,您只需实现以下内容(未针对性能进行优化)
In order to do what I wanted to do you can just implement the following (not optimized for preformance)
...
let customShouldHandle (req) {
const pattern = new require('url-patter')('/some/:key/path')
const url = require('url').parse(req.url).pathname
const match = pattern.match(url)
if (!match) {
return false
}
if (!req.params) {
req.params = {}
}
req.params.key = match.key
return true
}
...
let server = new WebSocket.Server({
server: httpServer,
path: this.customShouldHandle
})
...
这篇关于url 路径中带有通配符的 Node.js 和 Websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论