2017-10-10 82 views
0

我是新來signalr並創造了這個樣本項目,以獲取特定網站上的用戶數:Tutorial檢查一個webseite MIT signalr多少用戶,並重定向新用戶

這是運行良好。我的目標是隻有一個用戶訪問網站,如果第二個用戶想打開他應該重定向的頁面。我怎樣才能做到這一點?

如果我檢查頁面上的用戶並重定向,如果有多個用戶,則所有用戶都會重定向。確定信號器應該做什麼。

userActivity.client.updateUsersOnlineCount = function (count) { 
// Add the message to the page. 
    $('#usersCount').text(count); 
    if (count > 1) { window.document.location.href = "OPL.aspx"; } 
}; 

我怎麼能存儲在其中,我可以從後面的代碼訪問的的.cs數據類型的count?謝謝

回答

1

爲此,您需要兩種客戶端方法。 updateUsersOnlineCount有一項工作,即在線更新用戶以供所有人查看。然後你需要第二個客戶端方法,叫做redirectTheUser來重定向用戶。

在你的SignalR中心,你將實現OnConnectedOnReconnectedOnDisconnected事件,存儲(跟蹤)的連接ID,當計數達到一定的閾值,發送updateUsersOnlineCount給所有客戶提供Clients.All.updateUsersOnlineCount(msg), but send the message with客戶。客戶端(connectionId).redirectTheUser()`超過閾值的所有用戶。

舉例說明:

public override Task OnConnected() 
{ 
    string name = Context.User.Identity.Name; 
    _connections.Add(name, Context.ConnectionId); 
    // send to all above threshold 
    if(_connections.Count > threshold) 
      SendRedirect(_connections.Skip(threshold)); 
    return base.OnConnected(); 
} 

public override Task OnDisconnected(bool stopCalled) 
{ 
    string name = Context.User.Identity.Name;  
    _connections.Remove(name, Context.ConnectionId);  
    return base.OnDisconnected(stopCalled); 
} 

public override Task OnReconnected() 
{ 
    string name = Context.User.Identity.Name;  
    if (!_connections.GetConnections(name).Contains(Context.ConnectionId)) 
    { 
     _connections.Add(name, Context.ConnectionId); 
     // send to all above threshold 
     if(_connections.Count > threshold) 
      SendRedirect(_connections.Skip(threshold)); 
    }  
    return base.OnReconnected(); 
} 

private void SendRedirect(IEnumerable<string> connectionIds) 
{ 
    foreach (var connectionId in connectionIds) 
    { 
     Clients.Client(connectionId).redirectTheUser(); 
    } 
} 
+0

感謝您的回答。這使我指向了正確的方向。我是否理解該中心是針對整個網站的,因此無法檢查同一網站的不同網站,以便在每個網站上只允許一個用戶?謝謝 –

+0

更好的說,我可以得到用戶打開的頁面名稱或QueryString嗎?謝謝 –