Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build signalR+redis distributed chat Server

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

SignalR+redis distributed chat server is how to build, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

Recently, I need a chat server for a live broadcast project. I used to do it in a small way, and I didn't think too much about it, so there was only one server. A few days ago, suddenly 5000 people came, the server instant gg, as a developer I am very embarrassed! This is the background of our article.

I use C # Mvc4.0 to develop, here also need a redis as to whether you are the windows version or the Linux version, I don't care, anyway, there is an address and a port, the password is filled in according to the actual situation.

I use a demo here to show the distributed situation https://git.oschina.net/908Sharp/signalR-multi-Server.git

Step 1: create two new mvc projects

Add the following packages from nuget

Install-Package Microsoft.AspNet.SignalR

Install-Package Microsoft.AspNet.SignalR.Redis

Install-package Microsoft.Owin.Cors

Step 2: add the Owin StartUp class to the App_Start directory

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)

});

}

Pay attention to the quoted bags, slutty years.

Step 3: add the ChatHub class

[HubName ("chat")]

Public class ChatHub:Hub

{

Public void Chat (string msg)

{

Clients.All.Display ("Receive Msg:" + msg)

}

}

The back end is done.

Step 4: the creation of front-end pages

/ *

Signalr

1. Initialize the chat server

, /

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)

});

Remember that the demo I said above is two sites, the code is the same, in the formal environment, we must be a code deployed on different servers, pointing to the same redis address.

* Let me say that this thing is generated automatically, or you can specify it manually. I'd better post the code. You can also see F12 for yourself.

/ *!

* 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 ($.roomR)! = "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))

This piece is OK if you want to specify a specific path, but write this sentence in the background.

After reading the above, have you mastered how to build a signalR+redis distributed chat server? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report