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

大城市里の小女人 提交于 2020-01-06 15:52:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39197967/c-sharp-mvc-send-message-with-signalr-from-server-to-caller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!