zoukankan      html  css  js  c++  java
  • signalR聊天

    首先创建一个server端和client端,server端使用webapi,client使用mvc(也可以放个html就可以)

    Server

    引入Microsoft.AspNetCore.SignalR 包

    创建一个Hub类,用来建立连接,收发消息

    using Microsoft.AspNetCore.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    
    namespace IM.MsHub
    {
        public class MsServe : Hub
        {
            public MsServe()
            {
            }
            public override Task OnConnectedAsync()
            {
                 Clients.Client(Context.ConnectionId).SendAsync("open", new { msg = "连接开始" });
                return base.OnConnectedAsync();
               
            }
            public override Task OnDisconnectedAsync(Exception exception)
            {
                return base.OnDisconnectedAsync(exception);
            }
            public async Task sendmsg(string msgstr)
            {
               Dictionary<string,string> dic= JsonConvert.DeserializeObject<Dictionary<string, string>>(msgstr);
               await Clients.Client(Context.ConnectionId).SendAsync(dic["invokefun"], new { msg="发送消息:"+dic["text"] });
            }
        }
    }
    MsServe

    在statup文件中添加以下代码:

    ConfigServices 中添加

    Services.AddSignalR();

    Configure中 的UseEndpoints 添加 

    app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                    endpoints.MapHub<MsHub.MsServe>("/mshub");    
                });

    至此服务端完成了

     Client

    首次创建一个wwwroot文件夹,再创建一个client.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    
        
        <script src="aspnet/signalr/dist/browser/signalr.js"></script>
        <script src="/jquery/jquery.min.js"></script>
        <style type="text/css">
            #msg_div {
                border: 2px solid #0094ff;
                width: 90%;
                min-height: 300px;
                margin: 0 auto;
            }
        </style>
    </head>
    <body>
        <div id="msg_div"></div>
    
        <button onclick="send()">发送</button>
    </body>
    
    </html>
    
    <script type="text/javascript">
        var conn = null;
        setupconnection = () => {
            conn = new signalR.HubConnectionBuilder().withUrl("https://localhost:5001/mshub").build();
            //定义函数,供服务端调用客户端
            conn.on("js_msg", function (data) {
                $("#msg_div").append(data.msg+"<br/>");
            });
            //首次连接后,服务端调用,open为自定义,服务端与客户端协定
            conn.on("open", function (data) {
                $("#msg_div").append(data.msg + "<br/>");
            });
            conn.start().then(function () {
                //连接触发事件
            })
        }
        setupconnection();
        function send() {
            conn.invoke("sendmsg", json_str("发送的短消息","js_msg"));
        }
        function json_str(text, re_fun) {
            return JSON.stringify({ "text": text, "invokefun": re_fun });
        }
    </script>
    Client.html

    其中需要引用jquery.js 和aspnet signalr.js 

    在wwwroot文件夹上通过客户端库添加js

     选择unpkg输入signalr 下发会出现提示,可能会有点慢,请选择aspnet/signalr 选择特定文件,只选择signalr.min.js 就可以了

    jquery也这样安装就行,并将两个js引入html页。

    客户端js代码:

    setupconnection = () => {
            conn = new signalR.HubConnectionBuilder().withUrl("https://localhost:5001/mshub").build();
            //定义函数,供服务端调用客户端
            conn.on("js_msg", function (data) {
                $("#msg_div").append(data.msg+"<br/>");
            });
            //首次连接后,服务端调用,open为自定义,服务端与客户端协定
            conn.on("open", function (data) {
                $("#msg_div").append(data.msg + "<br/>");
            });
            conn.start().then(function () {
                //连接触发事件
            })
        }
        setupconnection();

    conn.on("",function(){})

    是定义函数,供服务端调用,当服务端能获取到客户端的方法就可以调用。

    我在客户端发送消息的代码中,增加了一个参数,将需要回调的函数名称传给了服务端,这样服务端按照参数值调用就可以了。

    仅供参考,内容中会引用部分博友的文章。(侵删)
  • 相关阅读:
    百度地图API 绘制矩形多边形等覆盖物
    不可多得的JS优化技巧
    vscode的settings.json配置(个人习惯)
    npm 查看模块全部版本
    .net core 生成 发布的文件里删除多余的语言包指定仅需要的语言
    225. Implement Stack using Queues (栈实现队列)
    232. Implement Queue using Stacks(队列实现栈)
    496. Next Greater Element I (单调栈)
    239. Sliding Window Maximum (滑动窗口最大值, 大根堆or 单调队列)
    30. Substring with Concatenation of All Words (滑动窗口)
  • 原文地址:https://www.cnblogs.com/zeran/p/14844944.html
Copyright © 2011-2022 走看看