.subscribe()
訂閱請求客戶端 socket 以接收一個或多個資料庫記錄的變更/刪除通知。
Something.subscribe(req, ids);
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | req | 包含要訂閱之 socket 的傳入 socket 請求 (req )。 |
|
2 | ids | 記錄 ID(主鍵值)的陣列。 |
當客戶端 socket 訂閱記錄時,它會成為其動態「記錄房間」的成員。這表示它將接收由 .publish()
廣播到該房間的所有訊息。
在伺服器端,於控制器動作中
// On the server:
if (!this.req.isSocket) {
throw {badRequest: 'Only a client socket can subscribe to Louies. But you look like an HTTP request to me.'};
}
// Let's say our client socket has a problem with people named "louie".
// First we'll find all users named "louie" (or "louis" even-- we should be thorough)
let usersNamedLouie = await User.find({ or: [{name: 'louie'},{name: 'louis'}] });
// Now we'll subscribe our client socket to each of these records.
User.subscribe(this.req, _.pluck(usersNamedLouie, 'id'));
// All done! We might send down some data, or just an empty 200 (OK) response.
然後,回到我們的客戶端程式碼中
// On the client:
// Send a request to the "subscribeToLouies" action, subscribing this client socket
// to all future events that the server publishes about Louies.
io.socket.get('/foo/bar/subscribeToLouies', function (data, jwr){
if (jwr.error) {
console.error('Could not subscribe to Louie-related notifications: '+jwr.error);
return;
}
console.log('Successfully subscribed.');
});
從現在開始,只要我們的請求客戶端 socket 保持連線,每當我們的伺服器端程式碼(例如,其他動作或 helpers)針對我們上面訂閱的 Louie 之一呼叫 User.publish()
時,它都會收到通知。
為了讓我們的客戶端程式碼處理這些未來的通知,它必須使用 .on()
監聽相關事件。例如
// On the client:
// Whenever a `user` event is received, say something.
io.socket.on('user', function(msg) {
console.log('Got a message about a Louie: ', msg);
});
請參閱概念 > 即時性,以取得更多關於 Sails/Socket.IO 中房間和事件之間差異的背景資訊。
對於某些應用程式,您可能會發現自己需要管理與同一記錄相關的兩個不同管道。若要完成此操作,您可以結合 .getRoomName()
和 sails.sockets.join()
// On the server, in your subscribe action…
if (!orgId) { throw 'badRequest'; }
if (!this.req.isSocket) { throw {badRequest: 'This action is designed for use with WebSockets.'}; }
let me = await User.findOne({
id: this.req.session.userId
})
.populate('globalAdminOfOrganizations');
// Subscribe to general notifications.
Organization.subscribe(this.req, orgId);
// If this user is a global admin of this organization, then also subscribe them to
// an additional private room (this is used for additional notifications intended only
// for global admins):
if (globalAdminOfOrganizations.includes(orgId)) {
let privateRoom = Organization.getRoomName(`${orgId}-admins-only`);
sails.sockets.join(this.req, privateRoom);
}
稍後,若要發布到這些房間之一,只需計算適當的房間名稱(例如「13-admins-only」),並使用 sails.sockets.broadcast()
廣播您的通知。
- 請務必檢查
req.isSocket === true
,然後再傳入req
以參照請求 socket。提供的req
必須來自 socket 請求,而不僅僅是任何舊的 HTTP 請求。.subscribe()
僅適用於透過 Socket.IO 連線(例如,使用io.socket.get()
)發出的請求,不適用於透過 HTTP 連線(例如,使用jQuery.get()
)發出的請求。請參閱sails.io.js
socket 客戶端文件,以取得關於使用客戶端 socket 與 Sails 傳送 WebSockets/Socket.IO 訊息的資訊。- 此函數實際上並未與資料庫互動!事實上,資源型 PubSub 方法都沒有。相反地,這些方法構成了建構在較低層級
sails.sockets
方法之上的簡化抽象層,旨在透過使用事件/房間/命名空間等的傳統名稱,使您的應用程式更簡潔且更易於偵錯。
req
)
res
)