SignalR is a library for real-time push, which can be used as a chat room or an instant message on the site. instant messaging is easy

What is SignalR?
ASP.NET SignalR is a library for ASP.NET developers that simplifies the process for developers to add real-time Web functionality to their applications. Real-time web functionality refers to functionality where server code can push content to connected clients as soon as they become available, rather than having the server wait for the client to request new data.
ASP.NET SignalR is a class library under ASP.NET, which can realize real-time communication in ASP.NET Web projects. What is the Web of real-time communication? It is to allow the client (Web page) and the server to notify each other of messages and call methods. Of course, this is a real-time operation.
WebSockets is a new API provided by HTML5. It can establish a Socket connection between a Web page and a server. When WebSockets is available (that is, the browser supports Html5), SignalR uses WebSockets. When it is not supported, SignalR will use other technologies to ensure the same effect. .
Of course, SignalR also provides a very simple and easy-to-use high-level API, so that the server can call JavaScript functions on the client individually or in batches, and it is very convenient for connection management, such as connecting the client to the server, or disconnecting, Client grouping, as well as client authorization, are very easy to implement using SignalR.
SignalR brings real-time communication with clients to ASP.NET. Of course, this is easy to use and has sufficient scalability. In the past, users needed to refresh the page or use Ajax polling to display real-time data, but now it can be easily realized by using SignalR.
The most important thing is that you don't need to rebuild the project, you can use SignalR seamlessly with your existing ASP.NET project. (Baidu Encyclopedia)

1: Add references and js
insert image description here

2. The code
uses signalr2, you need to create a new Startup.cs class, and the code is as follows:

using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
[assembly: OwinStartup(typeof(SignalrDemo.Startup))]
namespace SignalrDemo
{
    
       
    public class Startup
    {
    
    
        public void Configuration(IAppBuilder app)
        {
    
    
            app.MapSignalR();
 
        }
    }
}

The background also needs the ChatHub.cs class for group messaging, coded as follows:

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace SignalrDemo.Hubs
{
    
    
    [HubName("chatHub")]
    public class ChatHub:Hub
    {
    
    
        public void AddToRoom(string groupId,string userName)
        {
    
    
            //将分组Id放到上下文中
            Groups.Add(Context.ConnectionId, groupId);
            //群发人员进入信息提示
            Clients.Group(groupId, new string[0]).addUserIn(groupId,userName);
        }
        public void Send(string groupId,string detail,string userName)
        {
    
    
            //Clients.All.addSomeMessage(detail);//群发给所有
            //发给某一个组
            Clients.Group(groupId, new string[0]).addSomeMessage(groupId, detail,userName);
        }
    }
}

The front-end code is as follows:

@{
    
    
    ViewBag.Title = "Index";
    Layout = null;
}
<p>
    <span>房间号:</span>
    <input type="text" id="groupId" />
    <span>用户名:</span>
    <input type="text" id="userName" />
    <button id="joinRoom">加入聊天室</button>
</p>
<p>
    <span>消息:</span>
    <input type="text" id="message" />
    <button id="send">发送</button>
</p>
<div>
    <ul id="contentMsg">
    </ul>
</div>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
    $(function () {
    
    

        var chat = $.connection.chatHub;
        chat.hubName = 'chatHub';
        chat.connection.start();

        chat.client.addSomeMessage = function (groupId, detail,userName) {
    
    
            console.info("广播消息:" + detail);
            $("#contentMsg").append("<li>" + userName+": " + detail + "</li>");
        };

        chat.client.addUserIn = function (groupId,userName) {
    
    
            $("#contentMsg").append("<li>" + userName + "进入该聊天室!</li>");
        };
        $.connection.hub.logging = true;//启动signalr状态功能

        //加入聊天室 
        $("#joinRoom").click(function () {
    
    
            var groupId = $("#groupId").val();
            var userName = $("#userName").val();
            chat.server.addToRoom(groupId,userName);
        });
        //发送消息
        $("#send").click(function () {
    
    
            var detail = $("#message").val();
            var groupId = $("#groupId").val();
            var userName = $("#userName").val();
            chat.server.send(groupId,  detail, userName);
        });

    });
</script>

Three, pay attention to the place.

1. Referenced in the front-end page

This js. This is not found in the project, it is the js generated by signalr itself as a bridge.

2. An error may occur during the citation process.
"Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The found assembly manifest definition does not match the assembly reference. (Exception From HRESULT: 0x80131040)"
At this time, you can try to download web.config and add the following paragraph:

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

B:-->
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
<!--E-->

</assemblyBinding>


</runtime>

I feel a more detailed example: https://www.cnblogs.com/lgxlsm/p/7490139.html (from a great god)
recommend a demo on SignalR official website: http://www.asp.net/signalr/overview /getting-started/tutorial-getting-started-with-signalr
SignalR official website: http://www.asp.net/signalr

Guess you like

Origin blog.csdn.net/u014249305/article/details/107309841