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
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...