【问题标题】:SignalR - Works when deployed to Server, but stops after a few hours (MVC)SignalR - 部署到服务器时工作,但几个小时后停止(MVC)
【发布时间】:2018-02-20 01:02:33
【问题描述】:

编辑:查看这篇文章的底部以获取更新。

我的 SignalR 实现在我的本地系统上完美运行。但是当我将它部署到我的服务器时,它似乎不起作用。它是一个 MVC 项目。

我的signalR jQuery如下:

var clientHub = $.connection.gamehub;

$(function () {

    var signalRHubInitialized = false;

    var image = $("#Ico");

    var count = 0;

    initializeSignalRHubStore();

    function initializeSignalRHubStore() {

        if (signalRHubInitialized)
            return;

        try {

            clientHub.client.broadcastMessage = function (message) {
                if (message === "Refresh")
                    reloadIndexPartial();
            };

            $.connection.hub.start().done(function () {
                clientHub.server.initialize($("#NotifierEntity").val());
                signalRHubInitialized = true;
            });

        } catch (err) {
            signalRHubInitialized = false;
        }
    };

    function reloadIndexPartial() {
        //$.post('@(Url.Action("LivePartial", "Scrim", null, Request.Url.Scheme))')
        var id = $("#SeriesDetail_Id").val();
        $.post('/Scrim/LivePartial/' + id)
            .done(function (response) {
                try {
                    count = count + 1;
                    var favicon = new Favico({
                        animation: 'pop',
                        image: image
                    });
                    favicon.badge(count);
                }
                catch (exception) {

                }
                $("#summary-wrapper").html("");
                $("#summary-wrapper").html(response);
                if (!signalRHubInitialized)
                    initializeSignalRHubStore();
            });
    };
});

我下载了 Fiddler 看看发生了什么:

/signalr/hubs 返回一个 HTTP200

GET http://sitename.com/signalr/hubs HTTP/1.1
Host: sitename.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Accept: */*
Referer: http://sitename.com/scrim/Live/2835
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _gat=1; _ga=GA1.2.1342148401.1475084375; _gid=GA1.2.2092796788.1503865866

以 HTTP200 返回的协商

GET http://sitename.com/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22gamehub%22%7D%5D&_=1505151041506 HTTP/1.1
Host: sitename.com
Connection: keep-alive
Accept: text/plain, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://sitename.com/scrim/Live/2835
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _gat=1; _ga=GA1.2.1342148401.1475084375; _gid=GA1.2.2092796788.1503865866

连接,没有返回任何东西

GET http://sitename.com/signalr/connect?transport=serverSentEvents&clientProtocol=1.5&connectionToken=S8rqz2NPvVSJxbS1%2FpLm7yHTinGHWK1SnAwh8IfYA%2BP7nVb9RV%2FJzSFsf8Q%2BTv6Z%2Fae%2FIoZKlHKyeTxaEn3obg%2FVViYTB5HZxnrvKvtBZtQopvGPdj1i4o8Z9wGlCz3%2F&connectionData=%5B%7B%22name%22%3A%22gamehub%22%7D%5D&tid=10 HTTP/1.1
Host: sitename.com
Connection: keep-alive
Accept: text/event-stream
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Referer: http://sitename.com/scrim/Live/2835
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _gat=1; _ga=GA1.2.1342148401.1475084375; _gid=GA1.2.2092796788.1503865866

开始返回一个 HTTP200

GET http://sitename.com/signalr/start?transport=serverSentEvents&clientProtocol=1.5&connectionToken=S8rqz2NPvVSJxbS1%2FpLm7yHTinGHWK1SnAwh8IfYA%2BP7nVb9RV%2FJzSFsf8Q%2BTv6Z%2Fae%2FIoZKlHKyeTxaEn3obg%2FVViYTB5HZxnrvKvtBZtQopvGPdj1i4o8Z9wGlCz3%2F&connectionData=%5B%7B%22name%22%3A%22gamehub%22%7D%5D&_=1505151041507 HTTP/1.1
Host: sitename.com
Connection: keep-alive
Accept: text/plain, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://sitename.com/scrim/Live/2835
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _gat=1; _ga=GA1.2.1342148401.1475084375; _gid=GA1.2.2092796788.1503865866

发送返回一个 HTTP200

POST http://sitename.com/signalr/send?transport=serverSentEvents&clientProtocol=1.5&connectionToken=S8rqz2NPvVSJxbS1%2FpLm7yHTinGHWK1SnAwh8IfYA%2BP7nVb9RV%2FJzSFsf8Q%2BTv6Z%2Fae%2FIoZKlHKyeTxaEn3obg%2FVViYTB5HZxnrvKvtBZtQopvGPdj1i4o8Z9wGlCz3%2F&connectionData=%5B%7B%22name%22%3A%22gamehub%22%7D%5D HTTP/1.1
Host: sitename.com
Connection: keep-alive
Content-Length: 2227
Accept: text/plain, */*; q=0.01
Origin: http://sitename.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://sitename.com/scrim/Live/2835
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: _gat=1; _ga=GA1.2.1342148401.1475084375; _gid=GA1.2.2092796788.1503865866

data=%7B%22H%22%3A%22gamehub%22%2C%22M%22%3A%22Initialize%22%2C%22A%22%3A%5B%22%7B%5C%22SqlQuery%5C%22%3A%5C%22SELECT+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BId%5D+AS+%5BId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BGameGuid%5D+AS+%5BGameGuid%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BDate%5D+AS+%5BDate%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BTeamOneScore%5D+AS+%5BTeamOneScore%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BTeamZeroScore%5D+AS+%5BTeamZeroScore%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BTeamOneId%5D+AS+%5BTeamOneId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BTeamZeroId%5D+AS+%5BTeamZeroId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BGameVariantId%5D+AS+%5BGameVariantId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BMapId%5D+AS+%5BMapId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BDuration%5D+AS+%5BDuration%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BSeriesId%5D+AS+%5BSeriesId%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BResult%5D+AS+%5BResult%5D%2C+%5C%5Cr%5C%5Cn++++%5BExtent1%5D.%5BActive%5D+AS+%5BActive%5D%5C%5Cr%5C%5Cn++++FROM+%5Bdbo%5D.%5BGame%5D+AS+%5BExtent1%5D%5C%5Cr%5C%5Cn++++WHERE+(%5BExtent1%5D.%5BActive%5D+%3D+1)+AND+(%5BExtent1%5D.%5BSeriesId%5D+%3D+%40p__linq__0)%5C%22%2C%5C%22SqlConnectionString%5C%22%3A%5C%22Data+Source%3DWIN-1J1JAEOEU33%3BInitial+Catalog%3DSiteName%3BIntegrated+Security%3DTrue%3BMultipleActiveResultSets%3DTrue%3B%5C%22%2C%5C%22SqlParameters%5C%22%3A%5B%7B%5C%22CompareInfo%5C%22%3A0%2C%5C%22XmlSchemaCollectionDatabase%5C%22%3A%5C%22%5C%22%2C%5C%22XmlSchemaCollectionOwningSchema%5C%22%3A%5C%22%5C%22%2C%5C%22XmlSchemaCollectionName%5C%22%3A%5C%22%5C%22%2C%5C%22DbType%5C%22%3A11%2C%5C%22LocaleId%5C%22%3A0%2C%5C%22ParameterName%5C%22%3A%5C%22p__linq__0%5C%22%2C%5C%22Precision%5C%22%3A0%2C%5C%22Scale%5C%22%3A0%2C%5C%22SqlDbType%5C%22%3A8%2C%5C%22SqlValue%5C%22%3A%7B%5C%22IsNull%5C%22%3Afalse%2C%5C%22Value%5C%22%3A2835%7D%2C%5C%22UdtTypeName%5C%22%3A%5C%22%5C%22%2C%5C%22TypeName%5C%22%3A%5C%22%5C%22%2C%5C%22Value%5C%22%3A2835%2C%5C%22Direction%5C%22%3A1%2C%5C%22IsNullable%5C%22%3Afalse%2C%5C%22Offset%5C%22%3A0%2C%5C%22Size%5C%22%3A0%2C%5C%22SourceColumn%5C%22%3A%5C%22%5C%22%2C%5C%22SourceColumnNullMapping%5C%22%3Afalse%2C%5C%22SourceVersion%5C%22%3A512%7D%5D%7D%22%5D%2C%22I%22%3A0%7D

我已将此添加到我的网络配置中:

<modules runAllManagedModulesForAllRequests="true"></modules>

查看所有响应,似乎一切正常,但是当新条目添加到数据库时,我所在的页面没有更新。

在我的本地开发系统上,我的项目是使用 IIS 设置的,它可以完美运行。

谁能指点我正确的方向。

编辑:我现在已经在服务器上运行了。但它似乎在部署几个小时后就可以工作了。然后在那之后它似乎停止工作。所以我必须假设信号器连接在某个阶段被处理,现在正在恢复?

这是我的 RegisterServices 类:

private static IContainer RegisterServices(ContainerBuilder builder)
{
    builder.RegisterControllers(Assembly.GetExecutingAssembly());

    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

    builder.RegisterType<ContextEntities>()
           .As<DbContext>()
           .InstancePerRequest();

    builder.RegisterType<DbFactory>()
        .As<IDbFactory>()
        .InstancePerRequest();

    builder.RegisterType<UnitOfWork>()
        .As<IUnitOfWork>()
        .InstancePerRequest();

    // Services

    builder.RegisterType<MembershipService>()
    .As<IMembershipService>()
    .InstancePerRequest();

    builder.RegisterType<CacheService>()
    .As<ICacheService>()
    .InstancePerRequest();

    builder.RegisterType<GameHub>().ExternallyOwned();

    Container = builder.Build();

    return Container;
}

这里是使用signalr的页面:http://halodatahive.com/Scrim/Live/2845

在部署几个小时后,我似乎失去了对信号器连接的引用。

编辑:如果我回收我的 APP POOL,带有 signalR 的页面将再次开始工作。

【问题讨论】:

  • 您检查过 IIS/Web 服务器日志吗?如果您的应用程序在 Windows 服务器上崩溃,事件查看器中也应该有一个条目...您是否实现了应用程序日志?
  • 我现在将检查日志。如果应用程序崩溃,它不会重新启动并再次调用 app_start 代码吗?
  • 应用程序似乎很好。似乎没有任何崩溃。
  • 你检查过这个吗? stackoverflow.com/questions/10676270/…

标签: c# jquery asp.net-mvc signalr


【解决方案1】:

这就是我最终用来解决问题的方法。似乎在大约 1 小时后,它以某种方式断开了连接。我在几个小时前输入了这段代码,它似乎仍然有效。感谢@Noren 之前在聊天中提供的所有帮助!

编辑:不幸的是,这似乎并没有解决问题。

$.connection.hub.disconnected(function() {
    setTimeout(function() {
      $.connection.hub.start();
    }, 5000); // Restart connection after 5 seconds.
});

编辑:我想我会更新一下我是如何工作的。我没有使用SqlDependency 触发 SignalR,而是在调用_unitOfWork.Commit() 时在服务器上运行的计划任务上调用了Clients.All.broadcastMessage("Refresh");

某些原因导致 SqlDependency 停止工作,让它再次启动的唯一方法是回收应用程序池。

【讨论】:

  • 你现在可能已经解决了这个问题......无论如何,我使用上面的方法以及长轮询传输类型,并且一切似乎都运行良好。我认为最重要的是了解应用程序池何时空闲。对我来说,长轮询可以让它保持活力。
  • 我想我已经用上面的答案解决了这个问题,但是同一页面上有一个嵌入的流,当流处于实时状态时,它会抛出 JS 错误。所以我希望现在是这些错误导致了问题。但我还不确定。
【解决方案2】:

我以前见过这样的事情。在我的例子中,是因为 IIS 正在关闭应用程序而丢失了 RabbitMQ 事件。

您的应用程序是否经常受到攻击? IIS 倾向于关闭它认为不需要的应用程序以节省资源。这可能就是它在几个小时后才停止工作的原因,您可以回收以使其恢复正常。

See this answer.

【讨论】:

  • 我试过这个并将间隔设置为 0,但不幸的是问题仍然存在。
【解决方案3】:

首先在根目录下添加Hubs文件夹和NotificationsHubs.cs

在 NotificationsHubs.cs 中

[HubName("NotificationsHubs")]
public class NotificationsHubs : Hub
{

    public static Thread NotificationsThread;
    public void Send(string token, string UserAgent, string IP)
    {
        var serverVars = Context.Request.GetHttpContext().Request.ServerVariables;
        string SignalRIp = serverVars["REMOTE_ADDR"];

        string T = Context.Request.Headers["User-Agent"].ToLower();
        if ((T == cryptClass.crypt.Decrypt(UserAgent))  && (SignalRIp == cryptClass.crypt.Decrypt(IP)))
        {
            var connection = SignalRConnections.Connections.SingleOrDefault(c => c.Token == Guid.Parse(token));
            if (connection != null)
            {
                connection.Context = this.Context;
            }

            if (NotificationsThread == null || !NotificationsThread.IsAlive)
            {
               NotificationsThread = new Thread(new ThreadStart(NotificationsCheck));
                NotificationsThread.Start();
            }
        }

NotificationsCheck是自定义函数


NotificationController

public ActionResult Notifications()
{
    NotificationsModule.messageBL = _messageBL;
    long UserID = GetCurrentUser();
    Notification _Notification = new Notification();
    _Notification.GetToken = SignalRConnections.GetToken(UserID);
    _Notification.UserAgent = cryptClass.crypt.Encrypt(Request.UserAgent.ToLower());
    _Notification.IP = cryptClass.crypt.Encrypt(Request.UserHostAddress);
    return View(_Notification);
}

Notifications.cshtml 视图中

添加这个JS文件

    <script src="~/Scripts/jquery.signalR-2.2.1.js")"></script>
    <script src="~/signalr/hubs"></script>

$(function () {

    // Reference the auto-generated proxy for the hub.
    var chat = $.connection.NotificationsHubs;
    // Create a function that the hub can call back to display messages.
    chat.client.addNewMessageToPage = function (Title, Body, Icon) {
        // Add the message to the page.
        notifyMe(Title, Body, Icon);
    };

    $.connection.hub.start().done(function () {
        chat.server.send('@Model.GetToken', '@Model.UserAgent', '@Model.IP');
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.send();
        });
    });
});

notifyMe(Title, Body, Icon);是jquery自定义函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-04
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2018-12-19
    相关资源
    最近更新 更多