2

我正在尝试在现有的 MVC3 应用程序中实现 SignalR,以向所有连接的客户端发送警报。我正在使用持久连接。只是为了测试这一点,我在 _Layout 页面上放置了一个广播按钮。单击广播按钮使用 connection.send($('#msg').val()); 发送一些文本 并被客户成功接收。但这仅在应用加载时从第一页/默认页面广播消息时才有效。一旦页面被重定向,它就会失去连接,点击广播按钮会抛出错误消息“SignalR:必须先启动连接,然后才能发送数据。在 .send() 之前调用 .start()”。请指教。这是我的示例应用程序中的代码: 请注意,当我从 Home 导航到 About 时,连接会丢失。

<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.6.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.signalR.js")" type="text/javascript"></script>
<script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>

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

    connection.received(function (data) {
        alert(data);
    });

    connection.start();

    $("#broadcast").click(function () {
        connection.send($('#msg').val());
    });
});
</script>

</head>
<body>
<input type="text" id="msg" />         
<input type="button" id="broadcast" value="Broadcast" />
<ul id="messages"></ul> 
<div class="page">

    <div id="header">
        <div id="title">
            <h1>My MVC Application</h1>
        </div>

        <div id="logindisplay">
            @Html.Partial("_LogOnPartial")
        </div>

        <div id="menucontainer">

            <ul id="menu">
                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
            </ul>

        </div>
    </div>

    <div id="main">
        @RenderBody()
        <div id="footer">
        </div>
    </div>
</div>
</body>
4

1 回答 1

4

The connection will only be alive as long as the client is "alive". If you refresh the browser it will open a new connection. The issue you might be having is with the url you passed to the connection ctor.

If you're not using hubs then you don't need the ~/signalr/hubs included in your page.

If you navigate to http://{siteUrl}/echo in a new browser window, what does it say?

You might need to do something like:

var connection = $.connection('@Url.Content("~/echo")');

But that's based on how you mapped the route.

于 2011-11-02T22:25:48.217 回答