0

I am trying to implement SignalR notification hub using C# and Angular 8 for specific client.

I've successfully made the braodcast notification implementation for client specific using username validation which is also doing a broadcasting to all clients and validating username at angular side code.

Hardly trying to get this job done for specific client may be by registering connection-id/username where messages will be sent to a specific client or role-based clients.

I am sharing the code I have tried by using username but need some tweaks other way around(may be by registering connection-id/username). Please need your support.

I already checked all stackoverflow other posts on it but not providing specific answer on the same.

package.json:

{
  "name": "angular-client",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.2.0",
    "@angular/common": "~7.2.0",
    "@angular/compiler": "~7.2.0",
    "@angular/core": "~7.2.0",
    "@angular/forms": "~7.2.0",
    "@angular/platform-browser": "~7.2.0",
    "@angular/platform-browser-dynamic": "~7.2.0",
    "@angular/router": "~7.2.0",
    "@aspnet/signalr": "^1.1.4",
    "core-js": "^2.5.4",
    "font-awesome": "^4.7.0",
    "primeicons": "^1.0.0",
    "primeng": "^8.0.0-rc.1",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.13.0",
    "@angular/cli": "~7.3.8",
    "@angular/compiler-cli": "~7.2.0",
    "@angular/language-service": "~7.2.0",
    "@types/node": "~8.9.4",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.2.2"
  }
}

Angular - app.component.ts

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';

import * as signalR from '@aspnet/signalr';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MessageService]
})
export class AppComponent implements OnInit {

  constructor(private messageService: MessageService) { }

  ngOnInit(): void {
    const connection = new signalR.HubConnectionBuilder()
      .configureLogging(signalR.LogLevel.Information)
      .withUrl("http://localhost:5627/notify")
      .build();

    connection.start().then(function () {
      console.log('Connected!');
    }).catch(function (err) {
      return console.error(err.toString());
    });

    connection.on("BroadcastMessage", (type: string, payload: string, username: string) => {
      console.log("username:"+username);
      if(username == 'myuser') {
        this.messageService.add({ severity: type, summary: payload, detail: 'Via Apointment - '+username });
      }
    });
  }
}

C# - MessageController.ts:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SignalRHub;
using System;

namespace SignalR_Hub.Controllers
{
    [Route("api/message")]
    [ApiController]
    public class MessageController : ControllerBase
    {
        private IHubContext<NotifyHub, ITypedHubClient> _hubContext;

        public MessageController(IHubContext<NotifyHub, ITypedHubClient> hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage;



            try
            {
                // For Broadcasting
                //_hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload);
                //retMessage = "Success";

                // For Specific Client
                _hubContext.Clients.All.BroadcastMessage(msg.Type, msg.Payload, msg.Username);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }

            return retMessage;
        }
    }
}

Requesting using RestFul service:

{
 "Type": "info",
 "Payload": "One new Client is waiting for you.",
 "username": "myuser"
}

Please let me know if you need any information.

Arindam
  • 555
  • 1
  • 8
  • 24

1 Answers1

0

I believe that this question was answered here:

signalr-sending-a-message-to-a-specific-user

You can use connection ID and map it between and connectionID and an user.

Kiril1512
  • 3,231
  • 3
  • 16
  • 41
  • This does not help me in full as it mainly talks about C# .net side of code only. I need angular side implementation as well. – Arindam Sep 23 '19 at 09:53
  • you can see this git project with chats, because chats are done for client specific messaging or group specific messaging and it could help you. https://github.com/nrcpp/angular-asp.net-mvc-chat – Kiril1512 Sep 23 '19 at 10:00
  • I checked the github link. It says about chat but once I configured it at my local environment it says "Send message to All" which is again a broadcasting. Till now trying to crack it but no luck yet. – Arindam Sep 24 '19 at 23:53
  • Any solution till now ? – vijay sahu Dec 24 '20 at 17:03