SignalR Client Application fails to connect when r

2019-08-09 01:20发布

问题:

I have a sample SignalR JQuery client application which is almost identical to the GitHub JQuery example. If I run the application via VS2008, I get the following error: "SignalR: Connection must be started before data can be sent. Call .start() before .send()"

If I run the client app from the browser as in: http://localhost/SignalRClient, I get everything working as expected.

Any suggestions on how I can run the client with Visual Studio?

<div>
    <script type="text/javascript">
        $(function() {
            var connection = $.connection('http://localhost/signalrserver/echo');

            connection.received(function(data) {
                $('#messages').append('<li>' + data + '</li>');
            });

            connection.start();

            $("#broadcast").click(function() {
                connection.send($('#msg').val());
            });
        });
    </script>
    <input type="text" id="msg" />
    <input type="button" id="broadcast" />
    <ul id="messages"></ul>
</div>

Thanks.

回答1:

I ran into this issue as well. Since .start() is an asynchronous event, what's happening is you are calling .send() before the connection has been made. .start() takes a callback that is fired when the connection has been established. Your code then would look like this:

$(function() {
        var connection = $.connection('http://localhost/signalrserver/echo');

        connection.received(function(data) {
            $('#messages').append('<li>' + data + '</li>');
        });

        connection.start(function() {
            $("#broadcast").click(function() {
                connection.send($('#msg').val());
            });
        });
});