.publish()
向已 订阅 此模型 记录 之一或多个的套接字客户端广播任意消息。
Something.publish(ids, data, req);
此广播的事件名称与模型的标识相同。
参数 | 类型 | 详情 | |
---|---|---|---|
1 | ids | 记录 ID(主键值)数组。 | |
2 | data | 要广播的数据。 | |
3 | req | 可选。如果提供,则请求的套接字不会收到广播。 |
// On the server:
tellSecretToBobs: function (req, res) {
// Get the secret from the request.
var secret = req.param('secret');
// Look up all users named "Bob".
User.find({name: 'bob'}, function(err, bobs) {
if (err) {return res.serverError(err);}
// Tell the secret to every client who is subscribed to these users,
// except for the client that made this request in the first place.
// Note that the secret is wrapped in a dictionary with a `verb` property -- this is not
// required, but helpful if you'll also be listening for events from Sails blueprints.
User.publish(_.pluck(bobs, 'id'), {
verb: 'published',
theSecret: secret
}, req);
return res.send();
});
}
// On the client:
// Subscribe this client socket to Bob-only secrets
// > See the `.subscribe()` documentation for more info about subscribing to records:
// > https://sails.js.cn/documentation/reference/web-sockets/resourceful-pub-sub/subscribe
io.socket.get('/subscribeToBobSecrets');
// Whenever a `user` event is received, do something.
io.socket.on('user', function(msg) {
if (msg.verb === 'published') {
console.log('Got a secret only Bobs can hear:', msg.theSecret);
}
// else if (msg.verb === 'created') { ... }
// else if (msg.verb === 'updated') { ... }
});
- 请确保在将
req
传递给请求套接字之前检查req.isSocket === true
。如果使用,提供的req
必须来自套接字请求,而不是任何旧的 HTTP 请求。