有一个很酷的包叫做signalhub。它有一个 nodejs 服务器组件和可以在用户浏览器中使用的东西。它使用名为EventSource 的http (https) 协议的一个不太知名的应用程序。 EventSource 基本上会打开到 Web 服务器的持久 http (https) 连接。
这是一种可靠且轻量级的设置。 (README 讨论了 WebRTC 信号,但它的用处远不止于此。)
在服务器端,一个简单但有效的服务器设置可能如下所示:
module.exports = function makeHubServer (port) {
const signalhubServer = require('signalhub/server')
const hub = signalhubServer({ maxBroadcasts: 0 })
hub.on('subscribe', function (channel) {
/* you can, but don't have to, keep track of subscriptions here. */
})
hub.on('publish', function (channel, message) {
/* you can, but don't have to, keep track of messages here. */
})
hub.listen(port, null, function () {
const addr = hub.address()
})
return hub
}
在浏览器中你可以做这种事情。它用户 GET 来打开一个持久的 EventSource 来接收消息。而且,当需要发送消息时,它会发布消息。
而且,Chromium 的 devtools 网络选项卡了解所有有关 EventSource 连接的信息。
const hub = signalhub('appname', [hubUrl])
...
/* to receive */
hub.subscribe('a-channel-name')
.on('data', message => {
/* Here's a payload */
console.log (message)
})
...
/* to send */
hub.broadcast('a-channel-name', message)