如果连接未处于“已连接”状态,则无法发送数据。 -SignalR中的多个集线器

时间:2019-05-13 11:01:45

标签: asp.net-core signalr

我试图与SignalR保持联系,为此,我试图扩展Microsoft在其文档中提供的简单聊天室教程的功能。

我现在正在尝试添加第二个集线器,该集线器将允许用户以整数形式发送并接收乘以10的值。集线器本身与正常的ChatHub几乎相同,除了有一个额外的步骤可以检查输入是一个数字并进行乘法。

ChatHub

public class ChatHub : Hub
    {
        public async Task SendMessage(string group,string user, string message)
        {
            await Clients.Group(group).SendAsync("ReceiveMessage", user, message);
        }

        public async Task AddToGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
        }
    }

CalcHub

public class CalcHub : Hub
    {
        public async Task SendMessage(string group, string user, string message)
        {
            var value = MultiplyByTen(message);

            await Clients.Group(group).SendAsync("ReceiveMessage", user, value);
        }

        public async Task AddToGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
        }

        public string MultiplyByTen(string input)
        {
            bool isANumber = Int32.TryParse(input, out int value);

            if (isANumber)
            {
                return (value * 10).ToString();
            }

            return "Not a number";
        }
    }

我为前端设置了Javascript,当我尝试连接到ChatHub并发送消息时,它运行得很好,但是当我尝试使用与CalcHub的连接时,出现Cannot send data if the connection is not in the 'Connected' State错误消息。

这是建立两个连接的方式。

var calcConnection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44309/calcHub").build();
var chatConnection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44308/chatHub").build();
var activeConnection;

setConnection();

$("#hubSelector").on("change",
    function(data) {
        setConnection();
    });

我有一个简单的select元素,它将根据其值交换连接。 SetConnection是控制此方法的方法,DOM准备将其用于设置初始连接时使用。

这两个集线器也都注册在我的启动类中。

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("/chatHub");
                routes.MapHub<CalcHub>("/calcHub");
            });

如果我导航到集线器https://localhost:44309/calcHubhttps://localhost:44309/chatHub的两个地址,当我收到Connection ID required消息时,我还可以看到它们是有效地址。

为什么我的calcHub无法正常工作?

Site.js

// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.

// Write your JavaScript code.

$(function() {
    var calcConnection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44309/calcHub").build();
    var chatConnection = new signalR.HubConnectionBuilder().withUrl("https://localhost:44308/chatHub").build();
    var activeConnection;

    //setConnection();

    //$("#hubSelector").on("change",
    //    function(data) {
    //        setConnection();
    //    });




    activeConnection.on("ReceiveMessage", 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);
    });

    activeConnection.start().catch(function (err) {
        return console.error(err.toString());
    });



    $("#addgroup").on("click", function () {
        var group = document.getElementById("group").value;
        activeConnection.invoke("AddToGroup", group).catch(function (err) {
            return console.error(err.toString());
        });
        $("#group-list").append("<p>" + group + "</p>");
        event.preventDefault();
    });

    $("#sendButton").on("click", function () {
        var user = document.getElementById("userInput").value;
        var message = document.getElementById("messageInput").value;
        var group = document.getElementById("group").value;
        activeConnection.invoke("SendMessage", group, user, message).catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });

    function setConnection() {
        var selectValue = $("#hubSelector").val();

        if (selectValue === "chat") {
            $("#activeHub").html("<span>Active Hub: Chat</span>");
            activeConnection = chatConnection;
        }

        if (selectValue === "calc") {
            $("#activeHub").html("<span>Active Hub: Calc</span>");
            activeConnection = calcConnection;
        }

        console.log(activeConnection);
    }
});

0 个答案:

没有答案