.publish()
對訂閱一個或多個此模型紀錄的 socket 客戶端廣播任意訊息。
Something.publish(ids, data, req);
此廣播的事件名稱與模型的識別名稱相同。
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | ids | 紀錄 ID (主鍵值) 的陣列。 | |
2 | data | 要廣播的資料。 | |
3 | req | 選填。如果提供,則請求的 socket 將不會收到廣播。 |
// 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.dev.org.tw/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
以參照請求的 socket 之前,請務必檢查req.isSocket === true
。如果使用,提供的req
必須來自 socket 請求,而不僅僅是任何舊的 HTTP 請求。