聊天框Demo:DotNetCore+ActiveMQ+Mqttjs 實現前后台消息監聽


網上查了查 ActiveMQ + .net core 的例子很少,自己做一個demo 作為記錄,另外FineUI Core基礎版要來了,出來后我會用FineUI再做一版,為知識星球的引流...

1.安裝SDK 准備ActiveMQ 服務

此處用的 .net core 2.0+

此處用的 apache-activemq-5.9.0

2.創建項目

3.引用樣式

4.引用DLL

注意:先安裝 Apache.NMS.NetCore 再安裝 Apache.NMS.ActiveMQ.NetCore

 

 5.抄襲一個ActiveMQHelp

 來自 https://blog.csdn.net/PeterPan_hai/article/details/52354913

這里未做任何修改,正常添加引用即可

 

 

6.寫代碼

引用 paho-mqtt.js

 

 

直接重寫 View/Home/Index.cshtml

@{
    ViewData["Title"] = "全球都比較大的聊天室";
}
@section body{
    <h2>@ViewData["Title"]</h2>
    <form id="form1"></form>

}
@section Scripts{
    @*框架已經引用了*@
    @*<script src="~/js/MQTT/paho-mqtt.js"></script>*@
    <script>
        $(document).ready(function () {
            InitPage();//准備頁面
            ItinPahoClient();//准備鏈接
        });

        //核心方法:通過MQtt連接
        function ItinPahoClient() {
            //地址 端口 鏈接名稱(不是主題)
            var client = new Paho.Client("沒神的IP,大伙都知道", 61614, "jsclient");

            //監聽事件
            client.onMessageArrived = function (msg) {
                //收到消息
                messagebox.append("接收到消息:" + msg.payloadString);
                $('#textbox').val('');
            };

            //鏈接配置
            client.connect({
                onSuccess: function () {
                    messagebox.append('鏈接成功');
                    //訂閱主題為myqueue
                    client.subscribe("myqueue");
                    //發布消息,主題為myqueue2
                    //client.publish("myqueue2", "Message from js client");
                }
            });

        }
        //發送消息
        function setmessage() {
            var v = $('#textbox').val();
            bsEx.dopostback('@Url.Action("SetMessage")', {"msg":v}, function (t) {
                eval('(' + t + ')');
            });
        }

        ///初始化頁面
        function InitPage() {
            //表單
            new bsEx.ItemForm({
                id: "form1",
                renderto: '#form1',
                items: [
                    { type: 'textarea', name: 'messagebox', title: '消息', height: '300px' },
                    { type: 'text', name: 'textbox', title: '發送' }
                ],
                colunb: 1, showlabel: false, css: { 'width': '500px' }
            }).init().attr("onkeydown","if(event.keyCode == 13) { return false; }");

            //發送按鈕
            var btn = $('#textbox').addbutton("發送");
            btn.on('click', function () {
                setmessage();
            })

            $('#footer span').prepend("v" + $.fn.bsEx);
            //重寫append 加個回車
            messagebox = $('#messagebox');
            messagebox.append = function () {
                arguments[0] = arguments[0] +' \r\n  ';
                ($.fn.append).apply(this,arguments);
            }
            messagebox.append('...鏈接中');
        }

        //再text后面加一個button
        $.fn.addbutton = function (text) {
            $(this).parent().addClass('input-group');
            var bid = $(this).attr('id') + '-btn';
            var b = $('<span class="input-group-addon btn" id="' + bid + '">' + text + '</span >');
            $(this).after(b);
            $(this).attr("onkeydown", "if(event.keyCode == 13) { setmessage(); }");
            return $(b);
        }
    </script>
}

 注意:前台的核心方法 ItinPahoClient();

修改 Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ActiveMQTest.Controllers;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace ActiveMQTest
{
    public class Program
    {
        /// <summary>
        /// MQ
        /// </summary>
        public static ActiveMQHelp mymq { get; set; }

        public static void Main(string[] args)
        {
            //開始鏈接和訂閱主題
            mymq = new ActiveMQHelp(isLocalMachine: false, remoteAddress: "沒神的IP,大伙都知道");
        //主題名稱 myqueue 與前台一致 ,這里注意區分 topic 和 queue的區別 Program.mymq.InitQueueOrTopic(topic: true, name: "myqueue", selector: false); CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }

 修改 Controllers/HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ActiveMQTest.Models;

namespace ActiveMQTest.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SetMessage(string msg)
        {
            //發送
            Program.mymq.SendMessage(msg, "newid", priority: Apache.NMS.MsgPriority.Lowest);
            return Content("console.log(\""+ msg + "  發送成功\");");
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetMessage()
        {
            //后台拿一次
            return Content("console.log(\"" + Program.mymq.GetMessage() + "\");") ;
        }


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

 

 至此,代碼全部完成,可以運行,只要IP對,基本沒啥大問題,不會的問我,源碼這里下載

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM