最近在搞一个直播项目需要聊天服务器,之前是以小打小闹来做的,并没有想太多就只有一台服务器。前几天一下子突然来了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));
这一块是你要是想指定具体路径也是可以的哦,但是要在后台写这么一句话
结束。
我也刚刚写完,还没有放到正式环境去用,哈哈哈,捂嘴偷笑,吐血了吗? 现在我担心我们windows版本的redis不稳定。