@jamil,我在project上创建的代码是最好的,它正在工作。你能提供更多的细节或比较下面的代码。如果有什么不同,也告诉我。
--在Startup.cs中
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//DKS: Makes the SignalR services available to the dependency injection system.
services.AddCors(options => options.AddPolicy("CorsPolicy",
builder =>
{
builder.AllowAnyMethod().AllowAnyHeader()
.WithOrigins("http://localhost:53249")
.AllowCredentials();
}));
services.AddSignalR();
}
//运行时调用此方法。使用此方法配置http请求管道。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
---主页组件
import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
@Component({
selector: 'app-home-component',
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
private _hubConnection: HubConnection | undefined;
public async: any;
message = '';
messages: string[] = [];
constructor() {
}
public sendMessage(): void {
const data = `Sent by you: ${this.message}`;
if (this._hubConnection) {
this._hubConnection.invoke('SendAngular', data);
}
this.messages.push(data);
}
ngOnInit() {
let builder = new signalR.HubConnectionBuilder();
this._hubConnection = builder.withUrl("http://localhost:53249/chatHub", signalR.HttpTransportType.WebSockets).build();//'http://localhost:1874/notify').build();
this._hubConnection.serverTimeoutInMilliseconds = 9999999999999;
this._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log(err)); //'Error while establishing connection :('));
console.log(this._hubConnection);
this._hubConnection.on('Send', (data: any) => {
const received = `Received by Friend: ${data}`;
this.messages.push(received);
});
//this._hubConnection.onclose = e => {
// this._hubConnection.start();
//}
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRExample.Hubs
{
public class ChatHub : Hub
{
public Task SendAngular(string data)
{
return Clients.All.SendAsync("Send", data);
}
}
}