简体   繁体   English

从.NET客户端连接时未调用SignalR OnConnected

[英]SignalR OnConnected not called, connecting from .NET client

I'm using SignalR and have a Hub where I've overwritten the OnConnected method. 我使用的是SignalR,并且有一个集线器,其中我覆盖了OnConnected方法。 The reason is, the server publishes data every 60 seconds. 原因是,服务器每60秒发布一次数据。 But when a new client connects, I want to publish the data immediately. 但是,当有新的客户端连接时,我想立即发布数据。

In a simplified form: 以简化形式:

public class CustomerPublisher : Hub
{
    public void Publish(Customer customer)
    {
        Clients.All.receive(customer);
    }

    public override Task OnConnected()
    {
        return base.OnConnected();
    }
}

The OnConnected method is never called (I tested by debugging). 永远不会调用OnConnected方法(我通过调试进行了测试)。 I've read in several places (like here ) that the client needs to have a connected handler, like: 我已经在多个地方(如here )中阅读到,客户端需要具有连接的处理程序,例如:

$.connection.onlineHub.client.connected = function(){...}

However, I have a WPF client, so in .NET I tried adding this, on top of the event I was already handling: 但是,我有一个WPF客户端,因此在.NET中,除了已经处理的事件之外,我还尝试添加它:

hubProxy.On<object>("receive", OnCustomerReceived); // this line was already present
hubProxy.On<object>("connected", OnConnected); // I added this

This didn't help. 这没有帮助。 But I do have a connection, because after some time, I start receiving data. 但是我确实有连接,因为一段时间后,我开始接收数据。

Is there anything I'm missing? 有什么我想念的吗? How can I get SignalR to call the OnConnected method when my .NET client connects? 当.NET客户端连接时,如何让SignalR调用OnConnected方法?

You can try to use StateChanged event like this : 您可以尝试使用StateChanged事件,如下所示:

Connection.StateChanged += Connection_StateChanged;
void Connection_StateChanged(StateChange obj)
{
    if (obj.NewState == ConnectionState.Connected)
    {
          //do somethign here
    }
}

You ll receive Connecting and Connected states 您将收到ConnectingConnected状态

In my case, the problem was Autofac. 就我而言,问题是Autofac。 I had set it up in my own way (due to the way I had set up WCF duplex before using SignalR). 我已经按照自己的方式进行了设置(由于使用SignalR之前已经设置了WCF双工)。 But it is important to follow the docs . 但是遵循文档很重要。 Even though a connection was made, and my client received data, I never entered the OnConnected method. 即使建立了连接,并且我的客户端接收到数据,我也从未输入过OnConnected方法。 After following the documentation, I the method was called. 在遵循文档之后,我调用了该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM