使用 SignalR 从控制台向网页发送消息

Send message from console to web page using SignalR

我正在尝试使用 SignalR 从控制台应用程序向 MVC 应用程序发送消息, 以下是代码:

static void Main(string[] args)
    {

        string url = "http://localhost:8080";
        string line=null;
        MyHub obj = new MyHub();

        using (WebApp.Start(url))
        {
            Console.WriteLine("Server running on {0}", url);
            Console.ReadLine();

            Console.WriteLine("Enter your message:");
            line = Console.ReadLine();
            obj.Send(line);

        }
        
    }
}
class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}
public class MyHub : Hub
{
    public void Send(string message)
    {
        Clients.All.addMessage(message);
    }
}

以下是我尝试在网站上获取消息的方式:

<script type="text/javascript">
    $(function () {
        //Set the hubs URL for the connection
        $.connection.hub.url = "http://localhost:8080/signalr";

        // Declare a proxy to reference the hub.
        var chat = $.connection.myHub;

        // Create a function that the hub can call to broadcast messages.
        chat.client.addMessage = function (message) {
            // Html encode display name and message.
            //var encodedName = $('<div />').text(name).html();
            var encodedMsg = $('<div />').text(message).html();
            // Add the message to the page.
            $('#discussion').append('<li><strong>'
                + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        //$('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.
        //$('#message').focus();
        // Start the connection.

        
    });
</script>

问题是我收到以下异常:

感觉我无法直接实例化 class Myhub 的对象,关于如何解决这个问题的任何想法,请记住我需要将消息从控制台发送到网页。有什么建议吗? ??

使用 SignalR,您无需实例化集线器 classes,SignalR 会实例化,并且它不一定会两次使用相同的集线器实例。切勿将状态数据存储在集线器 class 本身中。

SignalR 使用中心上下文来跟踪客户端并允许您与他们交互。您需要从 SignalR 库中获取此上下文,然后才能发送信息等。IHubContext 为您提供了在中心使用的 ClientsGroups 成员,允许您执行与您在集线器中执行的操作相同。

试试这个:

static void Main(string[] args)
{
    string url = "http://localhost:8080";
    using (WebApp.Start(url))
    {
        Console.WriteLine("Server running on {0}", url);

        // get text to send
        Console.WriteLine("Enter your message:");
        string line = Console.ReadLine();

        // Get hub context 
        IHubContext ctx = GlobalHost.ConnectionManager.GetHubContext<MyHub>();

        // call addMessage on all clients of context
        ctx.Clients.All.addMessage(line);

        // pause to allow clients to receive
        Console.ReadLine();
    }
}