我正在使用在云中运行的 Azure SignalR 服务,并运行一个 Azure Function App,该应用程序在我的笔记本电脑的 localhost 上本地运行。我有以下中心:
public class LeaderboardHub : ServerlessHub
{
[FunctionName("negotiate")]
public async Task<SignalRConnectionInfo> Negotiate([HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req) =>
Negotiate(req.Headers["x-ms-signalr-user-id"]);
[FunctionName(nameof(OnConnected))]
public async Task OnConnected([SignalRTrigger]InvocationContext invocationContext, ILogger logger)
{
logger.LogInformation($"{invocationContext.ConnectionId} has connected");
}
}
Run Code Online (Sandbox Code Playgroud)
我像这样连接到我的集线器:
const apiBaseUrl = window.location.origin;
const connection = new signalR.HubConnectionBuilder()
.withUrl(apiBaseUrl + '/api')
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start()
.catch(console.error);
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我可以设置一个断点Negotiate()并查看所建立的连接。当我向我的中心发送消息时,它们会显示在客户端上。但是,我从未看到该OnConnected方法被调用。同样,如果我创建新的SignalRTrigger方法并在 Javascript 中调用它们,它们永远不会被调用。
我的理论:我希望我错了,但我有点猜测这是因为我在自己的笔记本电脑上的 localhost 下运行我的应用程序,而 Azure SignalR 服务无法将消息“转发”给我,因为 Azure 无法连接到我的笔记本电脑。我还没有尝试将我的函数应用程序部署到 Azure 并在那里运行它,但我猜测如果我在 Azure 中运行它,将会有双向连接。