Ste*_*fan 4 javascript websocket node.js
是否有一个用于node.js的websocket框架,我可以在其中指定websockets服务器路径中的通配符?
我想使用这样的路径
/一些/:id
在这种情况下,应该能够连接到与上述字符串匹配的 url。服务器可以访问id并可以为不同的频道提供服务。
例如:当使用模块“ws”时,可以为 http 服务器上的一个特定路径设置 websocket 服务器:
new WebSocket.Server({server: someHttpServer, path:'/some/path'})
Run Code Online (Sandbox Code Playgroud)
从这里开始,您可以使用 WebSocket 对象从浏览器连接到您的 websocket 服务器:
let client = new WebSocket('ws://.../some/path')
Run Code Online (Sandbox Code Playgroud)
我正在寻找的是这样的东西
new WebSocket.Server({server: someHttpServer, path:'/some/:id'})
Run Code Online (Sandbox Code Playgroud)
这样我就可以连接到 websocket 并传递预定义的 id
let clientA = new WebSocket('ws://.../some/idA')
let clientB = new WebSocket('ws://.../some/idB')
Run Code Online (Sandbox Code Playgroud)
由于没有答案,我认为实际上没有答案。
我发现 Websocket.Server 类中的 shouldHandle 方法负责决定请求的 websocket 路径。这可以很容易地被覆盖,如下所示:
WebSocket.Server.prototype.shouldHandle = function shouldHandle(req) {
// Add your own logic and return `true` or `false` accordingly.
};
Run Code Online (Sandbox Code Playgroud)
为了做我想做的事情,您只需实现以下内容(未针对性能进行优化)
...
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
})
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2694 次 |
| 最近记录: |