首页 > 解决方案 > 与 SignalR 聊天 | 角 8 | ASP.NET 核心 2.1

问题描述

我尝试通过聊天重复示例。这里这样。但正如我所了解的那样,我对主人的地址有疑问。这就是我的组件启动时所拥有的。

在此处输入图像描述

如您所见,我有两个地址。我只试过/chat但结果相同

我在 VS 中启动的应用程序。我不作为一个单独的客户端部分和 api-becked 开始。

这是我的应用程序的网址,我通过聊天开始我的组件。http://localhost:59955/home/message

我的代码

public class ChatHub : Hub
{
public async Task Send(string name, string message)
{
    await this.Clients.All.SendAsync("sendToAll", name, message);
}
}

启动和我添加的内容。

services.AddSignalR();
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
        builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("http://localhost:4200");
    }));

我的方法public void Configure(IApplicationBuilder app, IHostingEnvironment env)

app.UseSignalR(routes =>
    {
        routes.MapHub<Chat>("/chat");
    });

现在客户端

export class ChatComponent implements OnInit {
// tslint:disable-next-line:variable-name
private _hubConnection: HubConnection;
nick = '';
message = '';
messages: string[] = [];

constructor() { }

ngOnInit() {
this.nick = window.prompt('Your name:', 'John');

this._hubConnection = new 
 HubConnectionBuilder().withUrl('http://localhost:59955/chat').build();

 this._hubConnection
  .start()
  .then(() => console.log('Connection started!'))
  .catch(err => console.log('Error while establishing connection :('));
 }


public sendMessage(): void {
 this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string) 
 => {
  const text = `${nick}: ${receivedMessage}`;
  this.messages.push(text);
 });
 this._hubConnection
  .invoke('sendToAll', this.nick, this.message)
  .catch(err => console.error(err));
}
}

有launchSettings json 文件。

在此处输入图像描述

在什么问题上?

标签: angularasp.net-coresignalrasp.net-core-signalr

解决方案


我尝试从头开始在同一个项目中创建 SignalR 集线器服务器和 Angular 客户端,使用相同的代码创建集线器服务器并配置 SignalR。

对于 Angular 客户端,我发现这个包“ @aspnet/signalr-client ”已被弃用,所以我改用“ @aspnet/signalr ”。

该项目在我这边运行良好,没有错误,如果可能,您可以创建新项目或使用“ @aspnet/signalr ”来构建 SignalR Angular 客户端并检查它是否适合您。

角客户端

import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';
import signalR = require('@aspnet/signalr');

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

  constructor() { }

  private _hubConnection: HubConnection;

  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this._hubConnection = new signalR.HubConnectionBuilder()
      .withUrl("/chat")
      .build();

    this._hubConnection
      .start()
      .then(() => console.log('Connection started!'))
      .catch(err => console.log('Error while establishing connection :('));

    this._hubConnection.on('sendToAll', (nick: string, receivedMessage: string) => {
      const text = `${nick}: ${receivedMessage}`;
      this.messages.push(text);
    });
  }

  public sendMessage(): void {
    this._hubConnection
      .invoke('sendToAll', this.nick, this.message)
      .catch(err => console.error(err));
  }
}

测试结果

在此处输入图像描述


推荐阅读