简体   繁体   中英

C# MVC - Send message with SignalR from server to Caller

I have a request from client to Server using SignalR-2.2.1 . After that request, Server will send the results back to the caller. Here is my JavaScript code :

$(document).ready(function () {
    var myHub = $.connection.signalHub;
    myHub.client.receive = function (tmp) {
        var obj = $.parseJSON(tmp);
        //do something
    };
    $.connection.hub.start().done(function () {
        $('#xxxxx').click(function () {
            var form = $("form");
            form.submit();
            myHub.server.sendSomething();
        });
    }).fail(function (reason) {
       //do something
    });
});

And here is the code from my Server Side

public partial class SignalHub : Hub
{
    public void SendSomething()
    {
         Clients.All.receive(MyJson);
    }
}

When I use Clients.All function, it works perfectly fine. But what I want is the server only send the result back to the caller (the one that send the request). So I change Clients.All.receive(MyJson) to Clients.Caller.receive(MyJson) . After I change it, now the client doesnt update the content. Do I need to specify my receive function in client side that it would receive something different?

My guess is that since you are calling form.submit(); you are probably navigating away from the page or possibly reloading it, in that sense a new connection with a different "connectionId" is established between the new/reloaded page, thus the message intended for Client.Caller is lost since it is associated with the connection established on the page that you navigated away from or refreshed.

You might want to consider posting your form-data using AJAX instead of a full form submit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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