我正在学习SignalR,但遇到了障碍。
我有一个Azure功能,成功发布到Azure SignalR托管服务(在无服务器模式下配置)
我一直在关注这个快速入门:
Quickstart: Create a chat room with Azure Functions and SignalR Service using C#
我想要实现的是基本上从服务器接收消息到我的客户端应用程序。为了原型,我创建了一个控制台应用程序。
我添加了以下Nuget包
Microsoft.AspNetCore.SignalR.Client -Version 1.1.0 Microsoft.Azure.WebJobs.Extensions.SignalRService
所有的基础设施似乎都运行良好 - 我基于这样的假设我可以在以下地址运行演示网站,将其指向我的本地实例(或我在Azure中托管的实例)https://azure-samples.github.io/signalr-service-quickstart-serverless-chat/demo/chat-v2/
我的Azure功能发布的消息直接发布到聊天窗口。
如何将这些消息打印到控制台?
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using System;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();
var connection = new HubConnectionBuilder().WithUrl("http://localhost:7071/api").Build();
connection.On<SignalRMessage>("newMessage", (message) =>
{
Console.WriteLine(message.Arguments);
});
connection.On("newMessage", (string server, string message) =>
{
Console.WriteLine($"Message from server {server}: {message}");
}
);
await connection.StartAsync();
Console.ReadKey();
}
}
}
我强烈怀疑我的问题与此有关
connection.On <...>
声明。他们永远不会开火Connection.StartAsync()似乎工作正常,并建立与Azure SignalR实例的连接。
我错过了一些基本点吗?我只是在这一点上喋喋不休。
简而言之 - 有人可以给我一个指向RECEIVING和WRITING消息的指针到我的控制台窗口 - 就像在网络聊天演示中将消息打印到Web浏览器一样(参见上面的第二个链接)。
消息是简单的广播消息,我想要去所有连接的客户端。
几乎所有的例子都在Javascript中。
提前致谢。
一旦我发现如何向SignalR添加日志记录,我就会发现它无法解析正在发送的类型。
一旦我改变了我的连接,它就工作了。对于正确的类型,例如
connection.On<CorrectType>("newMessage", (message) =>
{
Console.WriteLine(message.stringproperty);
});
通过查看文章Azure Functions development and configuration with Azure SignalR Service,我的想法被误导了
他们“貌似”(至少在我的脑海中)向SignalR添加“SignalRMessage”类型的消息。实际上他们正在添加消息类型“CorrectType”
CorrectType message
signalRMessages.AddAsync(
new SignalRMessage
{
// the message will only be sent to these user IDs
UserId = "userId1",
Target = "newMessage",
Arguments = new [] { message }
});