且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SignalR:生成的代理与动态创建的集线器文件

更新时间:2023-09-18 19:18:10

如前所述 在这个 ASP.NET 页面关于使用带有 SignalR 的集线器:

As stated on this ASP.NET page about using hubs with SignalR:

生成的代理及其作用

您可以编写 JavaScript 客户端以与 SignalR 通信带有或不带有 SignalR 为您生成的代理的服务.什么代理为您做的是简化您使用的代码的语法连接,编写服务器调用的方法,并调用服务器上的方法服务器.

You can program a JavaScript client to communicate with a SignalR service with or without a proxy that SignalR generates for you. What the proxy does for you is simplify the syntax of the code you use to connect, write methods that the server calls, and call methods on the server.

当你编写代码调用服务器方法时,生成的代理使您能够使用看起来好像您正在执行本地函数:你可以写 serverMethod(arg1, arg2) 而不是调用('serverMethod',arg1,arg2).生成的代理语法也如果您输入错误,则启用立即且可理解的客户端错误服务器方法名称.如果您手动创建定义的文件代理,您还可以获得编写代码的 IntelliSense 支持调用服务器方法.

When you write code to call server methods, the generated proxy enables you to use syntax that looks as though you were executing a local function: you can write serverMethod(arg1, arg2) instead of invoke('serverMethod', arg1, arg2). The generated proxy syntax also enables an immediate and intelligible client-side error if you mistype a server method name. And if you manually create the file that defines the proxies, you can also get IntelliSense support for writing code that calls server methods.

长话短说:

如果您输入错误的 SignalR 集线器或方法名称,这会使您的生活更轻松,因为真正的 JS 错误.

This makes your life easier with real JS errors if you mistype SignalR hubs or method names.

使用代理:

var contosoChatHubProxy = $.connection.contosoChatHub;
contosoChatHubProxy.client.addContosoChatMessageToPage = function (name, message) {
    console.log(name + ' ' + message);
};

代理:

var connection = $.hubConnection();
var contosoChatHubProxy = connection.createHubProxy('contosoChatHub');
contosoChatHubProxy.on('addContosoChatMessageToPage', function(name, message) {
    console.log(name + ' ' + message);
});

如果您需要生成代理文件一次而不是在运行时生成它,您可以按照本部分,它允许您预先生成它(用于缓存或捆绑行为).

If you need to generate the Proxy file once instead of generating it at runtime, you can follow this section, which allows you generate it beforehand (for caching or bundling behavior).