简体   繁体   中英

SignalR hubclass in classlibrary

I have a signalr hubclass in a classlibrary

and when i use that hubclass in my webapplication referencing that class library with below javascript code, it does not work,

$(function () {

    var chat = $.connection.notificationHub;

    chat.client.newMessage = function (message) {
        alert(message);

        $('#messages').append('<li><strong>' +  message + '</strong>: </li>');
    };
    $.connection.hub.start();
});

You need an event to trigger your method in Hub class. See below example:

NotificationHub in the class library

public class NotificationHub : Hub
{
    public void Send(string message)
    {
        Clients.All.newMessage(message);
    }
}

Web application

<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<ul id="messages"></ul>

   <script src="~/Scripts/jquery-1.10.2.min.js"></script>
   <script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
   <script src="signalr/hubs"></script>

    <script>
        $(function () {
            var chat = $.connection.notificationHub;
            chat.client.newMessage = function (data) {
                //alert(data);
                $('#messages').append('<li><strong>' + data + '</strong>: </li>');
            };
            $('#message').focus();
            $.connection.hub.start().done(function () {
                console.log("Connected");
                $('#sendmessage').click(function () {
                    chat.server.send($('#message').val());
                    $('#message').val('').focus();
                });
            });
        });
    </script>

Note

Because you the hubclass is in the class library, you need to install Microsoft ASP.NET SignalR package in it. You also need to install it in the webapplication. Then add hubclass reference to webapplication. Add app.MapSignalR() in your Startup class, like below:

public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM