简体   繁体   中英

fail to connect signalR hub from javascript client

i am trying to connect to a signalr hub which is in another domain from javascript client.

my references in the page

`<script src="script/jquery-1.10.2.min.js"></script>
 <script src="script/jquery.mobile-1.4.3.min.js"></script>
 <script src="Scripts/jquery.signalR-2.1.2.min.js"></script>
 <script src="http://domain/SignalR/Hubs"></script>

<script type="text/javascript">

    $(function () {
        var myHub = $.connection.newHub;

        // Start the connection
        $.connection.hub.start();

        // Declare a function on the blog hub so the server can invoke it
        myHub.client.BroadcastMessage= function ( message) {
            alert(message);
        };
        myHub.server.SentInfo(" message");
}    

but the client fails to connect to hub.

$.connection.hub.start();

fails and in console if i try to invoke myHub.server.SentInfo(" message"); it gives error as

Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()

What am i missing.

Thanks in advance

In your JavaScript you need to have $.connection.hub.url = 'yourURL'; before naming your Hub variable ( var myHub = $.connection.newHub; ). You might have to play with the URL a little bit depending on how you have your Startup.cs file and CORS configured.

A signalR connection does not open instantly. You need to wait until the open connection promise is fulfilled. Try the following code

    $.connection.hub.start().done(function () {
        // Declare a function on the blog hub so the server can invoke it
        myHub.client.BroadcastMessage= function ( message) {
           alert(message);
        };

        myHub.server.SentInfo(" message");
    });

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