【发布时间】:2020-10-15 04:00:58
【问题描述】:
我最初试图设置我的服务器端 signalR HUB 以向客户端发送消息,但到目前为止还没有成功。
所以我决定尝试从客户端发送消息;并设置一个按钮来触发从客户端到服务器的消息。
我可以启动我的Core 3.1 项目(下图),并很好地设置集线器连接,但无法以任何方式验证服务器上是否正在接收消息。
事实上,我的服务器断点永远不会被命中。
<button mat-button (click)="sendClientMessage()"> Send Message </button>
TypeScript 组件:
sendClientMessage(): void {
this.notificationService.sendMessageToHub();
}
import { Injectable } from '@angular/core';
import * as signalr from '@microsoft/signalr';
import { SIGCONT } from 'constants';
@Injectable({
providedIn: 'root',
})
export class NotificationService {
private hubConnection: signalr.HubConnection;
hubMessage: string;
public startConnection = () => {
this.hubConnection = new signalr.HubConnectionBuilder()
.withUrl('https://localhost:44311/hub')
.configureLogging(signalr.LogLevel.Debug)
.build();
this.hubConnection
.start()
.then(() => {
console.log('Hub Connection started');
this.sendMessageToHub();
})
.catch((err) => console.log(`Error while starting connection: ${err}`));
this.hubConnection.serverTimeoutInMilliseconds = 50000;
}
public hubListener = () => {
this.hubConnection.on('messageReceived', (message) => {
this.hubMessage = message;
console.log(message);
});
}
public sendMessageToHub = () => {
if (this.hubConnection == undefined || this.hubConnection.state === signalr.HubConnectionState.Disconnected) {
this.startConnection();
} else {
this.hubConnection.send('NewMessage', 'client', 'You have a notification from the front end !')
.then(() => console.log('Message sent from client.'));
}
}
constructor() { }
}
我的服务器端核心项目 - Notifications.cs
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NotificationHub.Hubs
{
public class Notifications: Hub
{
public async Task NewMessage(long username, string message)
{
await Clients.All.SendAsync("messageReceived", username, message);
}
internal Task NewMessage(string v1, string v2)
{
throw new NotImplementedException();
}
}
}
当我点击上面的按钮时,它似乎向服务器发送了一些东西:
如果能帮助我让我的 Core 项目首先遇到这些断点,并查看 NewMessage 方法没有收到客户端消息的原因,我将不胜感激。
从那里我可以尝试弄清楚如何将消息从服务器发送到客户端(即使用一些 Timer 示例)。
谢谢。
【问题讨论】:
标签: signalr signalr-hub signalr.client asp.net-core-signalr