您好,登錄后才能下訂單哦!
signalR+redis分布式聊天服務器是如何搭建,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
最近在搞一個直播項目需要聊天服務器,之前是以小打小鬧來做的,并沒有想太多就只有一臺服務器。前幾天一下子突然來了5000人,服務器瞬間gg,作為開發人員的我很尷尬! 這就是我們這篇文章的背景。
我使用的是C# Mvc4.0 來開發的,這里還需要一個redis 至于你是windows版本還是Linux版本我就不管了,反正是要有個地址一個端口,密碼根據實際情況填寫。
我這里用一個demo來展現分布式的情況https://git.oschina.net/908Sharp/signalR-multi-Server.git
第一步:新建兩mvc項目
從nuget 中添加以下幾個包
Install-Package Microsoft.AspNet.SignalR
Install-Package Microsoft.AspNet.SignalR.Redis
install-package Microsoft.Owin.Cors
第二步:在App_Start目錄中添加Owin StartUp類
public void Configuration(IAppBuilder app)
{
GlobalHost.DependencyResolver.UseRedis("127.0.0.1", 6379, string.Empty, "SignalRBus");
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
EnableJSONP = true
};
map.RunSignalR(hubConfiguration);
});
}
注意引用的包啊,騷年們。
第三步:添加ChatHub 類
[HubName("chat")]
public class ChatHub:Hub
{
public void Chat(string msg)
{
Clients.All.Display("Receive Msg:" + msg);
}
}
后端就算完成了。
第四步:前端頁面的創建
<div id="chat-content"></div>
<input type="text" id="msg" name="name" value="" placeholder="請輸入聊天內容"/>
<input type="button" id="btn" name="name" value="發送" />
<script src="/Scripts/jquery-1.10.2.min.js"></script>
<script src="/Scripts/jquery.signalR-2.2.1.js"></script>
<script src="/Scripts/hub.js"></script>
<script>
/*
signalr
1、初始化聊天服務器
*/
conn = $.hubConnection();
conn.qs = {
};
conn.start().done(function () {
console.log('signalr success');
$('#btn').click(function () {
var msg = $('#msg').val();
chat.invoke("Chat", msg)
.done(function () {
console.log('signalr send success');
$('#msg').val('');
})
.fail(function (e) {
console.log('signalr send fail');
});
})
});
chat = conn.createHubProxy("chat");
chat.on("Display", function (msg) {
$('#chat-content').html($('#chat-content').html() + '<br/>' + msg)
});
</script>
記住我上面說的demo是兩個站哦,代碼都一樣的,正式環境的時候我們肯定是一份代碼在不同服務器上部署,指向同一個redis地址
***我說一下<script src="/Scripts/hub.js"></script> 這個東西是自動生成的,你也可以手動指定,我還是把代碼貼出來吧。你也可以F12自己去看。
/*!
* ASP.NET SignalR JavaScript Library v2.2.1
* http://signalr.net/
*
* Copyright (c) .NET Foundation. All rights reserved.
* Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
*
*/
/// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" />
/// <reference path="jquery.signalR.js" />
(function ($, window, undefined) {
/// <param name="$" type="jQuery" />
"use strict";
if (typeof ($.signalR) !== "function") {
throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js.");
}
var signalR = $.signalR;
function makeProxyCallback(hub, callback) {
return function () {
// Call the client hub method
callback.apply(hub, $.makeArray(arguments));
};
}
function registerHubProxies(instance, shouldSubscribe) {
var key, hub, memberKey, memberValue, subscriptionMethod;
for (key in instance) {
if (instance.hasOwnProperty(key)) {
hub = instance[key];
if (!(hub.hubName)) {
// Not a client hub
continue;
}
if (shouldSubscribe) {
// We want to subscribe to the hub events
subscriptionMethod = hub.on;
} else {
// We want to unsubscribe from the hub events
subscriptionMethod = hub.off;
}
// Loop through all members on the hub and find client hub functions to subscribe/unsubscribe
for (memberKey in hub.client) {
if (hub.client.hasOwnProperty(memberKey)) {
memberValue = hub.client[memberKey];
if (!$.isFunction(memberValue)) {
// Not a client hub function
continue;
}
subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue));
}
}
}
}
}
$.hubConnection.prototype.createHubProxies = function () {
var proxies = {};
this.starting(function () {
// Register the hub proxies as subscribed
// (instance, shouldSubscribe)
registerHubProxies(proxies, true);
this._registerSubscribedHubs();
}).disconnected(function () {
// Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs.
// (instance, shouldSubscribe)
registerHubProxies(proxies, false);
});
proxies['chat'] = this.createHubProxy('chat');
proxies['chat'].client = {};
proxies['chat'].server = {
send: function (message) {
return proxies['chat'].invoke.apply(proxies['chat'], $.merge(["send"], $.makeArray(arguments)));
},
sendOne: function (toUserId, message) {
return proxies['chat'].invoke.apply(proxies['chat'], $.merge(["sendOne"], $.makeArray(arguments)));
}
};
return proxies;
};
signalR.hub = $.hubConnection("/signalr", { useDefaultPath: false });
$.extend(signalR, signalR.hub.createHubProxies());
}(window.jQuery, window));
這一塊是你要是想指定具體路徑也是可以的哦,但是要在后臺寫這么一句話
看完上述內容,你們掌握signalR+redis分布式聊天服務器是如何搭建的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。