io.socket.on()
開始監聽來自 Sails 的 socket 事件,使用指定的 eventName
。當收到符合的事件時,觸發提供的回呼函式。
io.socket.on(eventName, function (msg) {
// ...
});
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | eventName | socket 事件的名稱,例如 'recipe' 或 'welcome' 。 |
|
2 | handlerFn | 事件處理器,當伺服器向此 socket 廣播通知時將被呼叫。僅當傳入的 socket 通知符合 eventName 時才會被呼叫。 |
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | msg | 來自 socket 通知的資料。 |
當客戶端收到符合指定事件名稱 (例如 'welcome'
) 的傳入 socket 通知時,此事件處理器會被呼叫。當伺服器直接向此 socket 廣播訊息,或向其所屬的房間廣播訊息時,就會發生這種情況。若要廣播 socket 通知,您需要使用 藍圖 API 或編寫一些伺服器端程式碼 (例如在 action、helper,甚至在命令列腳本中)。這通常透過以下方式之一實現
sails.sockets
)監聽 "order" 事件
io.socket.on('order', function onServerSentEvent (msg) {
// msg => {...whatever the server broadcasted...}
});
想像您正在為連鎖餐廳建立訂購系統
// In your frontend code...
// (This example uses jQuery and Lodash for simplicity. But you can use any library or framework you like.)
var ORDER_IN_LIST = _.template('<li data-id="<%- order.id %>"><p><%- order.summary %></p></li>');
$(function whenDomIsReady(){
// Every time we receive a relevant socket event...
io.socket.on('order', function (msg) {
// Let's see what the server has to say...
switch(msg.verb) {
case 'created': (function(){
// Render the new order in the DOM.
var newOrderHtml = ORDER_IN_LIST(msg.data);
$('#orders').append(newOrderHtml);
})(); return;
case 'destroyed': (function(){
// Find any existing orders w/ this id in the DOM.
//
// > Remember: To prevent XSS attacks and bugs, never build DOM selectors
// > using untrusted provided by users. (In this case, we know that "id"
// > did not come from a user, so we can trust it.)
var $deletedOrders = $('#orders').find('[data-id="'+msg.id+'"]');
// Then, if there are any, remove them from the DOM.
$deletedOrders.remove();
})(); return;
// Ignore any unrecognized messages
default: return;
}//< / switch >
});//< / io.socket.on() >
});//< / when DOM is ready >
請注意,此範例假設後端在某個時間點呼叫
.publish()
或.broadcast()
。這可能是透過自訂程式碼,或透過 藍圖 API。
'connect'
事件預設情況下,當 Sails socket 客戶端載入到頁面時,它會自動開始為您連線 socket。當使用預設的自動連線 socket (io.socket
) 時,您不必等待 socket 連線才可以使用它。換句話說,您可以立即監聽其他 socket 事件或呼叫諸如 io.socket.get()
之類的方法。Sails socket 客戶端會將您在此期間執行的任何操作排隊,然後在連線生效後自動重播。
因此,直接使用 'connect'
事件對於大多數應用程式來說不是必要的。但是,為了完整起見,值得一提的是,您也可以綁定自己的 'connect'
處理器
io.socket.on('connect', function onConnect(){
console.log('This socket is now connected to the Sails server.');
});
'disconnect'
事件如果 socket 與伺服器的連線中斷了—可能是因為伺服器重新啟動,或者客戶端遇到某種網路問題—可以處理 disconnect
事件,以便顯示錯誤訊息,甚至手動重新連線 socket。
io.socket.on('disconnect', function onDisconnect(){
console.log('This socket lost connection to the Sails server');
});
Socket 可以配置為自動重新連線。但是,從 Sails v1 開始,Sails socket 客戶端預設停用此行為。實際上,由於您的使用者介面可能錯過了斷線期間的 socket 通知,因此您幾乎總是希望手動處理任何相關的自訂邏輯。(例如,「檢查您的網路連線」錯誤訊息)。
- 請記住,socket 僅在其連線期間 (例如,只要瀏覽器標籤頁開啟) 或直到在伺服器上手動使用
.unsubscribe()
或.leave()
取消訂閱時,才會保持訂閱房間。- 當監聽來自資源型 PubSub 呼叫和藍圖的 socket 訊息時,事件名稱始終與呼叫模型的 identity 相同。例如,如果您有名為 "UserComment" 的模型,則模型的 identity (以及
UserComment.publish()
使用的 socket 事件名稱) 是 "usercomment"。- 在上下文中,socket 通知有時也稱為「伺服器發送事件」或「Comet 訊息」。