简体   繁体   English

使用 SignalR - Angular 将消息发送到特定浏览器选项卡页面(客户端)

[英]Send Message To Specific Browser Tab Page (Client) using SignalR - Angular

I'm using this piece of Web API C#.Net Core code to send a message from server to client:我正在使用这段 Web API C#.Net 核心代码从服务器向客户端发送消息:

public class Test : ITest
{
    private IHubContext<NotificationHub, ITest> _hub;

    public Test(IHubContext<NotificationHub, ITest> hub)
    {
        _hub = hub;
    }

    public async Task BroadcastMessage(string Type, string Payload)
    {
        await _hub.Clients.All.BroadcastMessage(Type, Payload);
    }
}

But It will send message to all clients but I only need to send the message to opened tab page (client) which is executing web API.但它会向所有客户端发送消息,但我只需要将消息发送到正在执行 web API 的打开的标签页(客户端)。 What should I do to do such thing?我该怎么做才能做这样的事情?

And here is Angular Codes:这是 Angular 代码:

import * as signalR from '@aspnet/signalr';
import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/components/common/messageservice';
import { LogState, ActivityLogType, ContentSearcherResult } from 'src/Model/StartContentSearcher';
import { PropertyRead } from '@angular/compiler';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  constructor(private messageService: MessageService) { }

  private connection: signalR.HubConnection;

  connect(accessToken) {
    if (!this.connection) {
      this.connection = new signalR.HubConnectionBuilder()
        .withUrl("http://localhost:8178/contentsearcherHub", { accessTokenFactory: () => accessToken }).build();

      this.connection.start().catch(err => console.error(err))
      this.connection.on("BroadcastMessage", (Type, Payload) => { console.log(Type, Payload) })
    }
  }

  ngOnInit(): void {
    this.connect("3076a225-f2f6-4c68-b894-08accb62bb90");

  }

  uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }

}

I only need to send the message to opened tab page (client) which is executing web API.我只需要将消息发送到正在执行 web API 的打开的标签页(客户端)。 What should I do to do such thing?我该怎么做才能做这样的事情?

After client started/established connection to hub server, we can get connection id of current connected client.客户端启动/建立与中心服务器的连接后,我们可以获得当前连接的客户端的连接 ID。 To broadcast message only to that specific client who is consuming API, you can modify and pass connection id(s) to BroadcastMessage method, like below.要仅向使用 API 的特定客户端广播消息,您可以修改连接 ID 并将其传递给 BroadcastMessage 方法,如下所示。

public async Task BroadcastMessage(string connectionId, string Type, string Payload)
{
    await _hub.Clients.Client(connectionId).BroadcastMessage(Type, Payload);
}

I have a Angular project and I use the Signalr inside it.我有一个 Angular 项目,我在其中使用 Signalr。 But when I get the connectionId, I can print it.但是当我得到connectionId时,我可以打印它。 But I can't assign it in the global variable.但我不能在全局变量中分配它。 This is my code:这是我的代码:

connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:8178/notifyHub").build();
connection.start().then(function () {
  connection.invoke("GetConnectionId").then(function (connectionId) {
   console.log(connectionId);
   // var temp=connectionId
  })
}).catch(err => console.error(err));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM