• SignalR 框架笔记1


    SignalR 框架

    关键文件

    客户端操作文件

    "use strict";
    
    //初始化连接
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub", { accessTokenFactory: () => "" }).build();
    
    //禁用发送按钮,直到建立连接
    document.getElementById("sendButton").disabled = true;
    
    //接收事件
    connection.on("ReceiveMessage1", function (user, message) {
        var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        var encodedMsg = user + " says " + msg;
        var li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
    });
    
    connection.on("over", function (message) {
        var msg = message + "结束";
        var li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messagesList").appendChild(li);
    
        document.getElementById("sendButton").disabled = true;
    });
    
    //建立连接,并启用发送按钮
    connection.start().then(function () {
        document.getElementById("sendButton").disabled = false;
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    //绑定发磅按钮事件
    document.getElementById("sendButton").addEventListener("click", function (event) {
        //获取参数
        var user = document.getElementById("userInput").value;
        var message = document.getElementById("messageInput").value;
        //执行方法SendMessage1
        connection.invoke("SendMessage1", user, message).catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    View Code

    服务端操作文件

        public class ChatHub : Hub
        {
            public async Task SendMessage1(string user, string message)
            {
                var abc = Context;
                if (message == "over")
                {
                    await Clients.All.SendAsync("over", "完成");
                    //return await Task.CompletedTask;
                    return;
                }
                message += ",ok";
                //发送到客户端,接收事件
                //await Clients.All.SendAsync("ReceiveMessage1", user, message);
                //向特定用户发送信息
                //await Clients.User(user).SendAsync("ReceiveMessage1", user, message);
    
                await Clients.Group("SignalR Users").SendAsync("ReceiveMessage1", user, message);
            }
    
            public override async Task OnConnectedAsync()
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, "SignalR Users");
                await base.OnConnectedAsync();
            }
        }
    View Code

    配置:

    //启用SignalR
    services.AddSignalR();    
            app.UseEndpoints(endpoints =>
                {
                    //设置Hub
                    endpoints.MapHub<ChatHub>("/chatHub");
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    
                });

    网页端:

    <div class="container">
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-2">User</div>
            <div class="col-4"><input type="text" id="userInput" /></div>
        </div>
        <div class="row">
            <div class="col-2">Message</div>
            <div class="col-4"><input type="text" id="messageInput" /></div>
        </div>
        <div class="row">&nbsp;</div>
        <div class="row">
            <div class="col-6">
                <input type="button" id="sendButton" value="Send Message" />
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-12">
            <hr />
        </div>
    </div>
    <div class="row">
        <div class="col-6">
            <ul id="messagesList"></ul>
        </div>
    </div>
    <script src="~/js/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chat.js"></script>
  • 相关阅读:
    移动端解决fixed和input弹出虚拟键盘时样式错位
    JS的面向对象
    js计算两个时间范围间的间隔秒数
    使用js过滤字符串前后的空格
    C#时间格式-摘自http://www.cnblogs.com/xiaogongzhu/p/3825600.html
    [dp/贪心]435. 无重叠区间-----经典问题
    【dp】Leetcode面试题 17.16. 按摩师
    [dp]Leetcode.376.摆动序列
    Leetcode 945 使数组唯一的最小增量
    LeetCode 365.水壶问题
  • 原文地址:https://www.cnblogs.com/myfqm/p/13031212.html
Copyright © 2020-2023  润新知