url 路径中带有通配符的 Node.js 和 Websocket

编程入门 行业动态 更新时间:2024-10-26 20:33:44
本文介绍了url 路径中带有通配符的 Node.js 和 Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-26 05:34:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1130556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   路径   url   Websocket   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!