未收到来自客户端的SignalR消息

时间:2020-06-24 19:32:34

标签: signalr signalr-hub signalr.client asp.net-core-signalr

最初,我试图设置服务器端SignalR HUB来向客户端发送消息,但到目前为止还没有成功。

因此,我决定尝试从客户端发送消息;并设置一个按钮以触发从客户端到服务器的消息。

我可以启动我的Core 3.1项目(如下图),并很好地建立集线器连接,但是无法以任何方式验证服务器上是否正在接收消息。 实际上,我的服务器断点永远不会被击中。

l

enter image description here 在我的html中:

<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() { }
}

我的服务器端Core项目-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();
        }
    }
}

当我单击上面的按钮时,它似乎向服务器发送了一些东西:

enter image description here

对于使我的Core项目首先达到这些断点并查看NewMessage方法未收到客户消息的任何帮助,我将不胜感激。

从那里我可以尝试弄清楚如何从服务器向客户端发送消息(例如,使用一些Timer示例)。

谢谢。

1 个答案:

答案 0 :(得分:0)

您要从客户端向服务器发送2个字符串,但已使服务器方法采用longstring,因此它们不匹配。如果查看服务器日志,则会看到一条消息,提示找不到该方法。

观察错误的另一种方法是从客户端调用invoke而不是send,这将期望服务器在完成hub方法后得到响应,或者在这种情况下为错误将从服务器发送。