Asp.net
SignalR(Hub) 可以發送除信號製造者以外的消息嗎?
我正在學習 SingalR(https://github.com/SignalR/SignalR)。
我真的很想向所有連接發送消息,但發起事件的人除外。
例如,
在聊天應用程序中,有三個客戶端(A、B、C)。
客戶端 A 鍵入消息“Hello”並點擊送出。
Clients.addMessage(data); 向所有客戶發送“Hello”(包括客戶 A)
我只想向客戶端 B 和 C 發送“Hello”。
我怎樣才能實現它?
// I think this can get all Clients, right? var clients = Hub.GetClients<Chat>();
今天無法在伺服器上過濾消息,但您可以阻止從客戶端發送給呼叫者的消息。如果您查看 signalr 上的一些範例,您會發現它們在一個方法(通常稱為 join)中為每個客戶端分配了一個生成的 id。每當您從集線器呼叫方法時,傳遞呼叫客戶端的 id,然後在客戶端進行檢查以確保客戶端的 id 與呼叫者不同。例如
public class Chat : Hub { public void Join() { // Assign the caller and id Caller.id = Guid.NewGuid().ToString(); } public void DoSomething() { // Pass the caller's id back to the client along with any extra data Clients.doIt(Caller.id, "value"); } }客戶端
var chat = $.connection.chat; chat.doIt = function(id, value) { if(chat.id === id) { // The id is the same so do nothing return; } // Otherwise do it! alert(value); };希望有幫助。