SignalR发送数据页面加载

时间:2012-08-30 20:01:06

标签: load signals

当我想要发送数据时,我正在获得一个问题o当页面加载时从集线器启动一个sub。生病了这个示例代码因为很短

这是我的chat.vb

 Imports System
 Imports System.Collections.Generic
 Imports System.Linq
 Imports System.Web
 Imports SignalR.Hubs

 Public Class Chat
    Inherits Hub
    Public Sub Send(message As String)
       ' Call the addMessage method on all clients
        Clients.addMessage(message)
    End Sub
 End Class

这是我的default.aspx

 <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
 <script src="Scripts/jquery.signalR-0.5.3.js" type="text/javascript"></script>
 <script src="signalr/hubs" type="text/javascript"></script>
 <script language="javascript" type="text/javascript">
    $(function () {
        // Proxy created on the fly
        var chat = $.connection.chat;

        // Declare a function on the chat hub so the server can invoke it
        chat.addMessage = function (message) {
        $('#messages').append('<li>' + message + '</li>');
        };

        $("#broadcast").click(function () {
           // Call the chat method on the server
           chat.send($('#msg').val());
       }); 
       // Start the connection
       $.connection.hub.start();
    });
 </script>
 </head>
 <body>
   <form id="form1" runat="server">
   <div style="position: absolute; left: 0; top: 0; height: 100%; width: 100%">
     <input type="text" id="msg" />
     <input type="button" id="broadcast" value="broadcast" /> 
     <ul id="messages">
     </ul>
   </div> 
   </form>
 </body>

我不想按下按钮,我希望他在加载页面时自行完成所有操作

当我这样说的时候

    <script language="javascript" type="text/javascript">
      $(document).ready(function () {
        // Proxy created on the fly
        var chat = $.connection.chat;

        // Declare a function on the chat hub so the server can invoke it
        chat.addMessage = function (message) {
        $('#messages').append('<li>' + message + '</li>');
        }; 

       chat.send('Hello World');

       // Start the connection
       $.connection.hub.start();
    });
 </script>

我遇到了连接问题 我收到此错误“SignalR:必须先启动连接才能发送数据。在.send()之前调用.start()”;

1 个答案:

答案 0 :(得分:0)

您必须在发送之前致电开始。

所以:

chat.send('Hello World');

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

应该是:

// Start the connection
$.connection.hub.start().done(function () {
    // Call the server side function AFTER the connection has been started
    chat.send('Hello World');
});

希望这有帮助!