signalR redis分布式聊天服务器搭建

发布时间:2025-05-20 02:28:08 作者:益华网络 来源:undefined 浏览量(2) 点赞(2)
摘要:最近在搞一个直播项目需要聊天服务器,之前是以小打小闹来做的,并没有想太多就只有一台服务器。前几天一下子突然来了5000人,服务器瞬间gg,作为开发人员的我很尴尬! 这就是我们这篇文章的背景。 我使用的是C# Mvc4.0 来开发的,这里还需要一个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);

        }

    }

后端就算完成了。

        第四步:前端页面的创建

            

<script src="/Scripts/hub.js"></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() + + 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.

 *

 */

///

///

(function ($, window, undefined) {

    ///

    "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不稳定。

二维码

扫一扫,关注我们

声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。

感兴趣吗?

欢迎联系我们,我们愿意为您解答任何有关网站疑难问题!

您身边的【网站建设专家】

搜索千万次不如咨询1次

主营项目:网站建设,手机网站,响应式网站,SEO优化,小程序开发,公众号系统,软件开发等

立即咨询 15368564009
在线客服
嘿,我来帮您!