C#MVC-使用SignalR从服务器向调用方发送消息 [英] C# MVC - Send message with SignalR from server to Caller

查看:100
本文介绍了C#MVC-使用SignalR从服务器向调用方发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 SignalR-2.2.1 从客户端到服务器的请求.在该请求之后,服务器会将结果发送回调用方.这是我的 JavaScript 代码:

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
    });
});

这是服务器端的代码

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

当我使用 Clients.All 函数时,它工作得很好.但是我想要的是服务器仅将结果发送回调用方(发送请求的方).因此,我将 Clients.All.receive(MyJson)更改为 Clients.Caller.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?

推荐答案

我的猜测是,由于您正在调用 form.submit(); ,因此您可能正在浏览页面或重新加载页面,从这个意义上说,在新的/重新加载的页面之间建立了一个具有不同"connectionId"的新连接,因此用于 Client.Caller 的消息丢失了,因为该消息与该页面上建立的连接相关联您导航离开或刷新.

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.

您可能要考虑使用AJAX而不是完整的表单提交来发布表单数据.

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

这篇关于C#MVC-使用SignalR从服务器向调用方发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆