SignalR 2 與mvc 5實現實時聊天功能

来源:https://www.cnblogs.com/S-mm/archive/2022/06/25/16387179.html
-Advertisement-
Play Games

效果圖先附上: 首先 這是我是參考 教程:使用 SignalR 2 和 MVC 5 實時聊天 | Microsoft Docs 先附上教程: 在“添加新項 - SignalRChat”中,選擇 InstalledVisual> C#>WebSignalR>,然後選擇 SignalR Hub 類 (v ...


效果圖先附上:

 

 首先 這是我是參考  教程:使用 SignalR 2 和 MVC 5 實時聊天 | Microsoft Docs

先附上教程:

 

 

 

 

  1. “添加新項 - SignalRChat”中,選擇 InstalledVisual> C#>WebSignalR>,然後選擇 SignalR Hub 類 (v2) 

  2. 將類 ChatHub 命名並添加到項目中。

    此步驟將創建 ChatHub.cs 類文件,並將一組支持 SignalR 的腳本文件和程式集引用添加到項目中。

  3.  

     

  4. 將新 ChatHub.cs 類文件中的代碼替換為以下代碼:

  5. using System;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    namespace SignalRChat
    {
        public class ChatHub : Hub
        {
            public void Send(string name, string message)
            {
                // Call the broadcastMessage method to update clients.
                Clients.All.broadcastMessage(name, message);
            }
        }
    }
    1. “添加新項 - SignalRChat”中選擇InstalledVisual> C#>Web”,然後選擇“OWIN 啟動類”。

    2. 將類 命名為 Startup 並將其添加到項目中。

    3.  

       

    4. 將 Startup 類中的預設代碼替換為以下代碼:

    5. using Microsoft.Owin;
      using Owin;
      [assembly: OwinStartup(typeof(SignalRChat.Startup))]
      namespace SignalRChat
      {
          public class Startup
          {
              public void Configuration(IAppBuilder app)
              {
                  // Any connection or hub wire up and configuration should go here
                  app.MapSignalR();
              }
          }
      }

      將前端視圖的樣式替換(註意是佈局頁 引用分部頁,不是普通的視圖)

    6. View Code

控制器

 

 如果實現了以上  效果如圖

 

 如果要實現側邊欄展示 那麼需要把內容替換一下

@{
    ViewBag.Title = "Chat";
    Layout = "~/Views/Shared/_LayoutChat.cshtml";
}
@using 奈班級學生管理系統.Models;

<style>
    #content {
        width: 263px;
        height: 100%;
      @*  border: 1px solid #808080;*@
        border-radius: 15px;
        @*background-image: url('../../jsCSSImg/Images/mmexport1655381646980.jpg');*@
        /*background-image: url('../../jsCSSImg/Images/QQ圖片20220616195500.gif');*/
    }

    #foot {
        position: fixed;
        bottom: 10px;
        margin-left: 10px;
        white-space: nowrap;
        /*不換行*/
    }
    .offcanvas {
        overflow:auto;

    }
    .offcanvas-body{
        margin-bottom:30px;
    }
    .ljjr {
        color: white;
        position: fixed;
        left: 30%;
        bottom: 55%;
        width: auto;
        height: 110px;
        font-size: 90px;
        font-family: 華文琥珀;
        border: 0px;
        /* border-radius: 20px; */
        background-color: rgb(255,0,0,0.0);
    }
</style>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<p id="UserName" style="display:none;">@ViewBag.name</p>
<p id="time" style="display:none;">@ViewBag.time</p>
<body>
    <div id="tsparticles"><canvas class="tsparticles-canvas-el" width="2133" height="1249" style="width: 100%; height: 100%; position: fixed; z-index: -1; top: 0px; left: 0px; background-color: rgb(255, 255, 255); pointer-events: initial;"></canvas></div>

  

</body>
<button class="ljjr" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">立即加入</button>

<div class="offcanvas offcanvas-end" style=" width:30%" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
    <div class="offcanvas-header">
        <h3 class="container">線上聊天欄</h3>
        <hr style="color:#ccc" />
        <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
    </div>

    <div class="offcanvas-body">
        <div class="" id="content">


            <ul id="discussion">
            </ul>
            <div id="foot">
                <input placeholder="快和線上小伙伴一起交流吧~" type="text" id="message" style="width: 230px; border: 1px solid #000000;height:32px;border-radius:5px;" />
                <input type="button" id="sendmessage" value="發送" class="btn" style="background-color: #000000; color: white; width: 22%; height: 32px; border-radius: 4px; " />
                <input type="hidden" id="displayname" />
            </div>
        </div>
    </div>

</div>



@section scripts {
    <script src="~/Scripts/tsparticles.preset.bigCircles.bundle.js"></script>
    <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.3.js"></script>
    @* <script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>*@
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        tsParticles.load("tsparticles", { preset: "bigCircles" });
       @* //在此代碼塊中,將在腳本中創建回調函數。*@
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                var time = $("#time").html();
               @* alert(time)*@
                $('#discussion').append('<p><strong>' + htmlEncode(name)
                    + '</strong>: ' + htmlEncode(message) +"&nbsp;&nbsp;&nbsp;"+time + '</p>');

            };

            // Get the user name and store it to prepend to messages.
            var name = $("#UserName").html()
           @* alert(name)*@
            $('#displayname').val(name);
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            //此代碼將打開與中心的連接
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }


    </script>

}
View Code

註意 有一些路徑需要改成自己的


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • mysql服務端整體架構 主要分為兩部分,server層和存儲引擎 server層包括連接器、查詢緩存、分析器、優化器、執行器等,涵蓋mysql的大多數核心服務過功能,以及所有的內置函數,所有跨存儲引擎的功能都在這一層實現,比如存儲過程,觸發器,視圖等 存儲引擎層負責數據等存儲和讀取,其架構模式是插 ...
  • tunm二進位協議在python上的實現 tunm是一種對標JSON的二進位協議, 支持JSON的所有類型的動態組合 支持的數據類型 基本支持的類型 "u8", "i8", "u16", "i16", "u32", "i32", "u64", "i64", "varint", "float", "s ...
  • 迎面走來了你的面試官,身穿格子衫,挺著啤酒肚,髮際線嚴重後移的中年男子。 手拿泡著枸杞的保溫杯,胳膊夾著MacBook,MacBook上還貼著公司標語:“加班使我快樂”。 面試官: 看你簡歷上用過MySQL,問你幾個簡單的問題吧。什麼是聚簇索引和非聚簇索引? 這個問題難不住我啊。來之前我看一下一燈M ...
  • Python中的字典 Python中的字典是另一種可變容器模型,且可存儲任意類型對象。鍵值使用冒號分割,你可以看成是一串json。 常用方法 獲取字典中的值 dict[key] 如果key不存在會報錯,建議使用dict.get(key),不存在返回None 修改和新建字典值 dict[key]=va ...
  • 事情的起因是收到了一位網友的請求,他的java課設需要設計實現迷宮相關的程式——如標題概括。 我這邊不方便透露相關信息,就只把任務要求寫出來。 演示視頻指路👉: 基於JavaFX圖形界面的迷宮程式演示_嗶哩嗶哩_bilibili 完整代碼鏈接🔎: 網盤:https://pan.baidu.com ...
  • Redis 的定義? 百度百科: Redis(Remote Dictionary Server ),即遠程字典服務,是一個開源的使用ANSI C語言編寫、支持網路、可基於記憶體亦可持久化的日誌型、Key-Value資料庫,並提供多種語言的API。 中文官網: Redis是一個開源(BSD許可),記憶體存 ...
  • 安裝 Redis # 首先安裝依賴gcc, 後面需要使用make編譯redis yum install gcc -y # 進入 /usr/local/src 目錄, 把源碼下載到這裡 cd /usr/local/src # 下載 redis 7.0.2 的源碼,github被牆,可以使用國內的地址 ...
  • 一、前言 項目中之前涉及到胎兒心率圖曲線的繪製,最近項目中還需要添加心電曲線和血樣曲線的繪製功能。今天就來分享一下心電曲線的繪製方式; 二、正文 1、胎兒心率曲線的繪製是通過DrawingVisual來實現的,這裡的心電曲線我也是採用差不多相同的方式來實現的,只是兩者曲線的數據有所區別。心電圖的數據 ...
一周排行
    -Advertisement-
    Play Games
  • 概述:這個WPF項目通過XAML繪製汽車動態速度表盤,實現了0-300的速度刻度,包括數字、指針,並通過定時器模擬速度變化,展示了動態效果。詳細實現包括界面設計、刻度繪製、指針角度計算等,通過C#代碼與XAML文件結合完成。 新建 WPF 項目: 在 Visual Studio 中創建一個新的 WP ...
  • 概述:在WPF中使用`WpfAnimatedGif`庫展示GIF動畫,首先確保全裝了該庫。通過XAML設置Image控制項,指定GIF路徑,然後在代碼中使用庫提供的方法實現動畫控制。這簡化了在WPF應用中處理GIF圖的過程,提供了方便的介面來管理動畫播放和暫停。 當使用 WpfAnimatedGif  ...
  • 您是否曾經訪問過一個網站,它需要很長時間載入,最終你敲擊 F5 重新載入頁面。 即使用戶刷新了瀏覽器取消了原始請求,而對於伺服器來說,API也不會知道它正在計算的值將在結束時被丟棄,刷新五次,伺服器將觸發 5 個請求。 為瞭解決這個問題,ASP.NET Core 為 Web 伺服器提供了一種機制,就 ...
  • 本章將和大家分享如何通過 Elasticsearch 實現自動補全查詢功能。 一、自動補全-安裝拼音分詞器 1、自動補全需求說明 當用戶在搜索框輸入字元時,我們應該提示出與該字元有關的搜索項,如圖: 2、使用拼音分詞 要實現根據字母做補全,就必須對文檔按照拼音分詞。在 GitHub 上恰好有 Ela ...
  • using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace OOP { pub ...
  • 概述:以上內容詳細介紹了在C#中如何從另一個線程更新GUI,包括基礎功能和高級功能。對於WinForms,使用`Control.Invoke`;對於WPF,使用`Dispatcher.Invoke`。高級功能使用`SynchronizationContext`實現線程間通信,確保清晰、可讀性高的代碼 ...
  • Nuget包 Microsoft.Extensions.Telemetry.Abstractions 包含的新的日誌記錄source generator,它支持使用[LogProperties]將整個對象作為State與日誌一起記錄。 我將展示一種方法來控制如何使用[LogProperties]對象 ...
  • 支持.Net/.Net Core/.Net Framework,可以部署在Docker, Windows, Linux, Mac。 常見的ORM技術(比如:Entity Framework,Dapper,SqlSugar,NHibernate,等…),它們不是在做Sql語句的程式化變種,就是在做Sq ...
  • 一、引言 在現代應用程式開發中,尤其是在涉及I/O操作(如網路請求、文件讀寫等)時,非同步編程成為了提高性能和用戶體驗的關鍵技術。C#作為.NET框架下的主流開發語言,提供了強大的非同步編程支持,通過async/await關鍵字,可以讓開發者以同步的方式編寫非同步代碼,極大地簡化了非同步編程的複雜性。本文將 ...
  • 一、引言 在.NET開發中,操作Office文檔(特別是Excel和Word)是一項常見的需求。然而,在伺服器端或無Microsoft Office環境的場景下,直接使用Office Interop可能會面臨挑戰。為瞭解決這個問題,開源庫NPOI應運而生,它提供了無需安裝Office即可創建、讀取和 ...