search
HomeBackend DevelopmentC#.Net TutorialExample code for implementing real-time web chat using SignalR

Example code for implementing real-time web chat using SignalR

May 25, 2018 pm 04:12 PM
.netasp.netmvcsignalrLive chat

This article mainly introduces Asp.net SignalR to use real-time Web chat example code, which has certain reference value. Interested friends can refer to it.

The content shared with you in this chapter is to use The Signal R framework creates a simple group chat function. It mainly explains how to use this framework in .Net's MVC. Since this project has official documents (all in English of course), I will not write a sharing article later. The main purpose is to let friends We have one more solution when we need to use Web real-time communication. After all, this is one of the solutions promoted by Microsoft.

SignalR Online Introduction

ASP.NET SignalR is a library provided for ASP.NET developers that can simplify the development of real-time Web applications. The process of adding functionality to an application. A real-time web feature is a feature where server code can push content to a connected client as soon as it becomes available, rather than having the server wait for the client to request new data.

SignalR of course also provides a very simple and easy-to-use high-level API, which allows the server to call JavaScript functions on the client individually or in batches, and it is very convenient to perform connection management, such as the client connecting to the server. , or disconnection, client grouping, and client authorization are all 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 achieve real-time display of data. Now they can simply use SignalR. The most important thing is that you don't need to re-create the project, you can use SignalR seamlessly using your existing ASP .NET project.

Group chat instance effect

Let’s take a look at the effect of the test case first, rendering:

The interface is extremely simple. The style will not be considered here. The main purpose is to show its usage. The functions involved here are:

1. Count the number of online people

2. Display the nickname and connection method of the number of people online (this test case supports webSockets and longPolling (long connection))

3. Group chat information

How to use MVC Using SignalR

First, we create an MVC Web project as usual, and then add SignalR through the Nuget console command: Install-package Microsoft.AspNet.SignalR Dependencies, the automatically added packages are as follows:

 <package id="Microsoft.AspNet.SignalR" version="2.2.2" targetFramework="net45" />
 <package id="Microsoft.AspNet.SignalR.Core" version="2.2.2" targetFramework="net45" />
 <package id="Microsoft.AspNet.SignalR.JS" version="2.2.2" targetFramework="net45" />
 <package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.2.2" targetFramework="net45" />

and automatically add related js files to the Script folder in the MVC project:

jquery.signalR-2.2. 2.min.js

jquery.signalR-2.2.2.js

Then, we need to create a class with the file name Startup.cs in the project first-level directory, inside The main content cannot be completed:

[assembly: OwinStartup(typeof(Stage.Api.Extend.Startup))]
namespace Stage.Api.Extend
{
  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
      app.MapSignalR("/chat", new Microsoft.AspNet.SignalR.HubConfiguration
      {
        EnableDetailedErrors = true,
        EnableJavaScriptProxies = true
      });
    }
  }
}

First we analyze the attention points from top to bottom:

1. OwinStartup(Type) ConstructorTransfer is a type, and this type corresponds to the Startup class we created, which marks the starting position through this constructor class;

2. namespace Stage.Api.Extend is me Namespace of the project, this can be defined at will;

3. public void Configuration(IAppBuilder app) The function is fixed and necessary, here the program will first enter this method Execute the logic code inside;

4. app.MapSignalR is the extended IAppBuilder interface method. It has many forms of expression. Here I choose public <a href="http://www.php.cn/wiki/188.html" target="_blank">static</a> IAppBuilder MapSignalR(this IAppBuilder builder, <a href="http://www.php.cn/wiki/57.html" target="_blank">string</a> path, HubConfiguration configuration); , here it looks a bit similar to our MVC routing, The main thing to note here is the Path parameter, which needs to be used in the front-end page;

The configuration required in the background has actually been completed here. The following is the specific business logic processing class that needs to be operated. Create a new A class (here I named it ChatHub) and inherits Hub (which is provided by the SignalR framework), and the logic code inside is as follows:

public class ChatHub : Hub
  {
    //
    public int Num = 10001;
    public static List<MoHubUser> _Users = new List<MoHubUser>();

    /// <summary>
    /// 添加聊天人
    /// </summary>
    /// <param name="user"></param>
    public void AddUser(MoHubUser user)
    {

      user.Id = Context.ConnectionId;
      if (!_Users.Any(b => b.Id == user.Id))
      {
        _Users.Add(user);
      }

      //Clients.All.newUser(user);
      Clients.All.userList(_Users);
    }

    /// <summary>
    /// 发送信息
    /// </summary>
    /// <param name="user"></param>
    /// <param name="message"></param>
    public void SendAll(MoHubUser user, string message)
    {
      Clients.All.addNewMessageToPage(user, message);
    }

    /// <summary>
    /// 某个聊天人退出是,通知所有在线人重新加载聊天人数
    /// </summary>
    /// <param name="stopCalled"></param>
    /// <returns></returns>
    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
      var user = _Users.SingleOrDefault(x => x.Id == Context.ConnectionId);
      if (user != null)
      {
        _Users.Remove(user);
        Clients.All.userList(_Users);
      }
      return base.OnDisconnected(stopCalled);
    }
  }

上面的3个方法分别做了:添加聊天人到List,发送信息到客户端,某个连接失效后通知各个有效的聊天人重新加载信息;这里值得关注的是通过重新 public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) 方法来实现捕获并移除失效连接(这里是聊天人的信息);整篇测试用例通过Context.ConnectionId来保证连接的唯一性,只要有新的链接请求,那么服务端就会分配一个唯一串给这个链接,当客户端关闭页面或关闭链接这个是有就能在OnDisconnected方法中捕获到这个失效的链接的ConnectionId,这样就达到了移除失效聊天人的要求了;为了代码的方便性,这里创建了一个聊天人信息类:

public class MoHubUser
  {

    public string Id { get; set; }
    public string NickName { get; set; }
    public string TransportMethod { get; set; }
  }

到这里后台的聊天室代码就完成了就是这么简单;我们再来看试图中如何来写代码,这里我先给出我的html布局代码:

 @{
  ViewBag.Title = "神牛聊天室 - SignalR";
}
<style type="text/css">
  .p_left {
    width: 70%;
    float: left;
  }

  .p_right {
    width: 28%;
    float: left;
  }

  .ul {
    list-style: none;
    border: 1px solid #ccc;
    height: 500px;
    overflow-y: scroll;
    color: black;
  }

    .ul li {
      padding-top: 5px;
      padding-right: 25px;
    }

  .ul_user {
    list-style: none;
  }

    .ul_user li {
      padding-top: 5px;
    }

  .send {
    position: relative;
    background: #eae7e7;
    border-radius: 5px; /* 圆角 */
    padding-top: 4px;
    padding-left: 5px;
    margin-top: 13px;
  }

    .send .arrow {
      position: absolute;
      top: -16px;
      font-size: 0;
      border: solid 8px;
      border-color: #fff #fff #eae7e7 #fff;
    }
</style>
<h3 id="ViewBag-Title-nbsp-在线人数-span-nbsp-id-sapnUserTotal-span-人">@ViewBag.Title 在线人数:<span id="sapnUserTotal">0</span>人</h3>
<p class="container text-left">
  <p class="p_left">
    <ul class="ul" id="discussion"></ul>
    <textarea rows="5" class="form-control" id="message" maxlength="500" placeholder="开始聊天. . ." style="max-width: 100%"></textarea><br />
    <input type="button" id="sendmessage" value="发 送" class="btn btn-default" />
    <input type="hidden" id="displayname" />
  </p>
  <p class="p_right">
    <ul id="users" class="ul_user"></ul>
  </p>
</p>

<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
@*<script src="~/chat/hubs"></script>*@

客户端这里写法大致有两种选择,一种直接使用生成的代理来操作,一种不用自动生成的代理采用手动创建代理的方式;为了内容的简洁性,这里只简单讲解下自动生成的代理方式,而更多的是分享手动创建代理链接的方式;

使用生成的代理获取链接

首先,我们需要通过Script标签来引用一下自动生成代理的路径: <script src="~/chat/hubs"></script> ,注意啦这里的路径/chat对应的就是咋们在前面Startup.cs文件中配置 app.MapSignalR("/chat" 路径,而后面/hubs固定的写法(至少目前我还没更多的试验过),只有先应用了这个~/chat/hubs,才能在后面使用生成的代理,先上段代码:

var chat = $.connection.chatHub;
    chat.client.newUser = function (user) {
      $("#users").append(&#39; <li><strong>&#39; + user.NickName + &#39;[&#39; + user.TransportMethod + &#39;]</strong></li>&#39;);
    };

    chat.client.userList = function (users) {
      console.log(users);
      $("#sapnUserTotal").html(users.length);
      $.each(users, function (i, item) {
        $("#users").append(&#39; <li>[&#39; + item.TransportMethod + &#39;] <strong>&#39; + item.NickName + &#39;</strong>(&#39; + item.Id + &#39;)</li>&#39;);
      });
    };
    chat.client.addNewMessageToPage = function (user, message) {
      console.log(user);
      $("#discussion").append(&#39; <li ><span><strong>&#39; + user.NickName + &#39;[&#39; + user.TransportMethod + &#39;]</strong>:</span><p class="send">&#39; + message + &#39;<p class="arrow"></p></p></li>&#39;);
    };
  //connection.hub.start({ transport: [&#39;webSockets&#39;, &#39;longPolling&#39;] }).done(function () {
    //  my.TransportMethod = connection.hub.transport.name;
    //  chat.server.addUser(my);

    //  $(&#39;#sendmessage&#39;).click(function () {
    //    //console.log(chat);
    //    var content = $.trim($(&#39;#message&#39;).val());
    //    if (content.length <= 0) { $(&#39;#message&#39;).val(&#39;&#39;).focus(); return; }
    //    chat.server.sendAll(my, content);
    //    $(&#39;#message&#39;).val(&#39;&#39;).focus();
    //  });
    //}).fail(function () {
    //  alert("链接聊天室失败,请重新刷新页面。");
    //});

咋们逐步来解析下代码注意点:

1.  var chat = $.connection.chatHub; 这里的chatHub对应的就是咋们创建的并继承Hub的ChatHub类,由于js变量开头都是小写,所以这里是chatHub,这句活就表示链接到咋们后端了ChatHub类了,然后就可以使用里面的方法啦(这种有点类似于早期的webform中某种ajax请求的写法)

2. 通过chat.client.xxx来接收服务端通知的消息,而这个xxx对应的方法名称和咋们后端的Clients.All.xxx,本章实例对应的是:chat.client.userList = function (users){}对应Clients.All.userList(_Users);这样后端就能直接通知客户端的对应方法了;注意这里我后端Clients.All用的是通知全部客户端的意思,如果您需要通知指定的链接需要用到的是: T Client(string connectionId); 方法

3. chat.client是后端调用客户端,那相对的chat.server就是客户端请求服务端,和上面一样通过chat.server.xxx来指定请求的服务端方法,注意这个时候服务端方法指的是继承类Hub的子类的公共方法(本篇对应的是:chat.server.sendAll(my, content)对应ChatHub.cs文件中的 public void SendAll(MoHubUser user, string message) 函数)

4.  connection.hub.start({ transport: ['webSockets', 'longPolling'] }) 来指定运行的交互协议

以上就是使用生成代理的方式,按照上面的注意点来写应该不是问题;

使用手动创建反向代理来链接

不采用生成的代码的方式,我们只需要修改前端就行了,后台代码不用变或设置不用变动;首先我们把上面说的Script引用自动代理的代码去掉,因为这个时候不需要了,我们还是先上代码:

var my = { NickName: "神牛001", TransportMethod: "" };
    var connection = $.hubConnection("/chat/hubs");
    var chat = connection.createHubProxy(&#39;chatHub&#39;);

    chat.on("userList", function (users) {
      console.log(users);
      $("#sapnUserTotal").html(users.length);
      $("#users").html("");
      $.each(users, function (i, item) {
        $("#users").append(&#39; <li>[&#39; + item.TransportMethod + &#39;] <strong>&#39; + item.NickName + &#39;</strong>(&#39; + item.Id + &#39;)</li>&#39;);
      });
    });

    chat.on("addNewMessageToPage", function (user, message) {
      console.log(user);
      $("#discussion").append(&#39; <li ><span><strong>&#39; + user.NickName + &#39;[&#39; + user.TransportMethod + &#39;]</strong>:</span><p class="send">&#39; + message + &#39;<p class="arrow"></p></p></li>&#39;);

      var p = document.getElementById(&#39;discussion&#39;);
      //p.scrollTop = p.scrollHeight;
      p.scrollTop = 999999;
    });

    var nickName = prompt("请输入一个昵称:", my.NickName);
    my.NickName = nickName.length > 0 ? nickName : my.NickName;
    $(&#39;#displayname&#39;).val(nickName);
    $(&#39;#message&#39;).focus();
   

    connection.start({ transport: [&#39;webSockets&#39;, &#39;longPolling&#39;] }).done(function () {

      my.TransportMethod = connection.transport.name;
      //console.log(my.TransportMethod);
      chat.invoke("addUser", my);

      $(&#39;#sendmessage&#39;).click(function () {
        var content = $.trim($(&#39;#message&#39;).val());
        if (content.length <= 0) { $(&#39;#message&#39;).val(&#39;&#39;).focus(); return; }

        chat.invoke("sendAll", my, content);
        $(&#39;#message&#39;).val(&#39;&#39;).focus();
      });
    });

同样列出如下注意点:

1.  var connection = $.hubConnection("/chat/hubs"); 创建链接,这里的path同样对应后端的 app.MapSignalR("/chat" ,路径保持一致

2.  var chat = connection.createHubProxy('chatHub'); 来创建反向代理链接,这里的name:chatHub对应的是后端的ChatHub类名称

3. 通过on("xxx",function(){})函数来绑定服务端通知客户端的事件,xxx对应Clients.All.xxx中的xxx

4.  connection.start({ transport: ['webSockets', 'longPolling'] }) 来设置允许的链接方式,并开始链接

5. connection.transport.name来获取链接的方式名称,默认start不设置的话有这么几种:webSockets,foreverFrame,serverSentEvents,longPolling

6. chat.invoke("xxx", param1, param2) uses invoke to map the public methods of classes that inherit class Hub. The example here corresponds to: chat.invoke("sendAll", my, content ) Corresponds to public void SendAll(MoHubUser user, string message)

The above is the detailed content of Example code for implementing real-time web chat using SignalR. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.