我開發了一個網頁,連接到使用angularjs連接到jQuery代碼的signalR集線器。當發生一個sqldependency.onchange
事件時,客戶端會發送一條消息,但是,對於連接的每個客戶端而言,消息都被複制到每個客戶端。因此,如果連接兩個客戶端,則每個客戶端都會收到兩條消息,依此類推。SqlDependency的SignalR重複消息更改
步驟如下:
- 兩個客戶端連接到集線器
- 製作DB變化
- sqlDependency.onchange火災
- 呼叫中心功能
clients.all.renewProducts()
- 重新創建數據程序存儲庫重置依賴
- 客戶端控制檯:
"Database SQL Dependency change detected: Update" app.js:44:12 (Twice)
Hub.cs
public static void SignalRGetData(string data)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<SignalRGetData>();
context.Clients.All.renewData(data);
// Recereate data and sql dependency
new DataRespository().GetData();
}
DataRespository.cs _dependency_OnChange
public void _dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if(e.Info == SqlNotificationInfo.Update)
{
ProductHub.GetProducts("Database SQL Dependency change detected: " + e.Info);
}
}
的GetData
public IEnumerable<ProductInventoryDetail> GetData()
{
using(var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DynamicPricing"].ConnectionString))
{
conn.Open();
var reposQuery =
"SELECT [ID], [Program] FROM [DBO].[Detail]";
using(SqlCommand cmd = new SqlCommand(reposQuery, conn))
{
// remove any command object notifications
cmd.Notification = null;
// create dependency
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(_dependency_OnChange);
if (conn.State == System.Data.ConnectionState.Closed)
conn.Open();
// Execute Sql Command
using(var reader = cmd.ExecuteReader())
{
return reader.Cast<IDataRecord>().Select(x => new ProductInventoryDetail(){
ID = x.GetInt32(0),
Program = x.GetInt32(1)
}
}
}
}
}
角的JavaScript
// Apply jQuery SignalR operations to Angular
app.value('$', $);
app.factory('signalRService', ['$', '$rootScope', function ($, $rootScope) {
var proxy = null;
var initialise = function() {
// Get Connection to SignalR Hub
var connection = $.hubConnection();
// Create a Proxy
proxy = connection.createHubProxy('SignalRData');
// Publish the event when server has a push notification
proxy.on('renewProducts', function (message) {
console.log("Database SQL Dependency change detectedgnalRGetData: " + message);
$rootScope.$emit('renewProducts', message);
});
// Start Connection
connection.start().done(function() {
console.log("Conenction Ready - invoke proxy");
proxy.invoke('SignalRGetData');
});
};
return {
initialise: initialise
}
}]);
是否有可能在同一頁面上連接兩次? (通過在不同的控制器中初始化兩次)。 – sirrocco
定義角度服務會是這種情況嗎? – goingsideways
不,但是如果您在同一頁面上有兩個控制器,並且它們都獲得了signalRService並且都調用初始化方法 - 則會打開兩個連接。 – sirrocco