我如何订阅SignalR On活动?

时间:2015-02-01 19:45:55

标签: c# windows-store-apps windows-phone-8.1 signalr

我尝试对我的WP 8.1应用程序实现一些SignalR调用,但是我对On方法有一些问题。我可以连接到服务器,我可以使用Invoke方法通过信号器将数据发送到服务器。我可以通过下一个命令从服务器接收数据:

proxy.Subscribe("newTransaction").Received += newTransactionMethod;
async void newTransactionMethod(IList<Newtonsoft.Json.Linq.JToken> obj)
{
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { UpdateOutput2(obj[0]); });
}

void UpdateOutput2(dynamic data)
{
    if (data != null)
    {
        NewTransaction nt = JsonConvert.DeserializeObject<NewTransaction>(data.ToString());
        Output2.Text = "From: " + nt.fromName + " , To: " + nt.toName + " , Amount: " + nt.amount;
    }
}

但是我想使用On方法,而不是订阅,因为这是推荐的,更容易使用。我的问题是,当我尝试使用On方法时,它无法正常工作:我无法从服务器获取任何数据。可能我不能用它。
我尝试了什么:

proxy.On<string>("newTransaction", data =>
{
    Output2.Text = data;
});

好的,我没有在这里使用JsonConvert,但我可以在获取数据后序列化它。
任何人都可以帮我解决我的问题吗?

修改
这是完整的代码,也许它将有助于调查问题。

public sealed partial class SignalrPage : Page
{
    HubConnection connection;
    IHubProxy proxy;

    public SignalrPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        SignalR1();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
    }

    public async void SignalR1()
    {
        try
        {
            connection = new HubConnection("https://***");
            proxy = connection.CreateHubProxy("***Hub");

            await connection.Start(new WebSocketTransport());

            if (connection.State == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected)
                Output.Text = "Connected";

            var s = await proxy.Invoke<LoginData>("RegisterDevice", new LoginData()
            {
                UserName = "***",
                Password = "***",
                DeviceId = "***",
                DeviceType = 10
            });
            Output.Text = s.DeviceRegistered.ToString();

            //If I uncomment the next line and comment the proxy.On method is it working. But in this case not.
            //proxy.Subscribe("newTransaction").Received += newTransactionMethod;

            proxy.On<string>("newTransaction", data =>
            {
                Output2.Text = data;
            });

            Output3.Text = "It should be subscribed to newTransaction";
        }
        catch (Exception e)
        {
            Output.Text = e.ToString();
        }
    }

    async void newTransactionMethod(IList<Newtonsoft.Json.Linq.JToken> obj)
    {
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { UpdateOutput2(obj[0]); });
    }

    void UpdateOutput2(dynamic data)
    {
        if (data != null)
        {
            NewTransaction nt = JsonConvert.DeserializeObject<NewTransaction>(data.ToString());
            Output2.Text = "From: " + nt.fromName + " , To: " + nt.toName + " , Amount: " + nt.amount;
        }
    }

}

1 个答案:

答案 0 :(得分:0)

startHub: function () {
    $.connection.hub.url = self.hubUrl;  // ie. "https://rasxps:8082/signalR";

    // capture the hub for easier access
    var hub  = $.connection.queueMonitorServiceHub;

    // This means the <script> proxy failed - have to reload
    if (hub == null) {
        self.viewModel.connectionStatus("Offline");                
        toastr.error("Couldn't connect to server. Please refresh the page.");
        return;
    }

    // Connection Events
    hub.connection.error(function (error) {                
        if (error)
            toastr.error("An error occurred: " + error.message);
        self.hub = null;
    });
    hub.connection.disconnected(function (error) {                
        self.viewModel.connectionStatus("Connection lost");
        toastr.error("Connection lost. " + error);                

        // IMPORTANT: continuously try re-starting connection
        setTimeout(function () {                    
            $.connection.hub.start();                    
        }, 2000);
    });            

    // map client callbacks
    hub.client.writeMessage = self.writeMessage;
    hub.client.writeQueueMessage = self.writeQueueMessage;            
    hub.client.statusMessage = self.statusMessage;
    …

    // start the hub and handle after start actions
    $.connection.hub
        .start()
        .done(function () {
            hub.connection.stateChanged(function (change) {
                if (change.newState === $.signalR.connectionState.reconnecting)
                    self.viewModel.connectionStatus("Connection lost");
                else if (change.newState === $.signalR.connectionState.connected) {
                    self.viewModel.connectionStatus("Online");

                    // IMPORTANT: On reconnection you have to reset the hub
                    self.hub = $.connection.queueMonitorServiceHub;
                }
                else if (change.newState === $.signalR.connectionState.disconnected)
                    self.viewModel.connectionStatus("Disconnected");
            })     
        .error(function (error) {
            if (!error)
                error = "Disconnected";
            toastr.error(error.message);
        })
        .disconnected(function (msg) {
            toastr.warning("Disconnected: " + msg);
        });

        self.viewModel.connectionStatus("Online");                

        // get initial status from the server (RPC style method)
        self.getServiceStatus();
        self.getInitialMessages();                    
    });            
},

这是一个典型的集线器启动/错误处理程序例程。