【发布时间】:2021-05-01 15:12:18
【问题描述】:
我有一些类似聊天的应用程序。后端当然是 .net 核心,前端是 Angular。我的问题在于收到第一条聊天消息后,SignalR 连接会自动断开。我在后端覆盖了 OnDisconnectedAsync 方法,但我在那里收到的异常对象为空。角度与错误对象的 onclose 方法的情况相同。我在浏览器日志中得到以下信息:
[2021-01-27T18:05:34.398Z] Information: Connection disconnected. Utils.js:209
有趣的是,这第一条消息已成功提供给 Angular 应用程序并显示在网页上。 我尝试使用
Object.defineProperty(WebSocket, 'OPEN', {value: 1});
但同样的情况也会发生。 我的角码:
startConnection() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost.:80/' + 'chats')
.build();
this.hubConnection
.start()
.then(() => this.hubConnection.invoke<boolean>('RegisterConnection').then(value => {
if (!value.valueOf()) {
throw new Error('HUBMESSAGE: error returned from web api.');
}
}))
.catch(err => console.log('HUBMESSAGE: Error while starting connection: ' + err));
this.hubConnection
.onclose(error => {
console.log('HUBMESSAGE: err occur: ' + error);
console.log('State: ' + this.hubConnection.state);
});
}
getData(): Observable<MessageStatus> {
return this.data.asObservable();
}
changeChatId(chatId: number) {
this.hubConnection.invoke<boolean>('AssingToChat', chatId).then(value => {
if (!value.valueOf()) {
throw new Error('HUBMESSAGE: error returned from web api.');
}
})
.catch(err => console.log('HUBMESSAGE: Error while starting connection: ' + err));
}
addTransferChartDataListener() {
console.log('HUBMESSAGE: listen');
this.hubConnection.on('chatchartdata', (data) => {
console.log('Received hub chat data: ' + JSON.stringify(data))
const streamStatus: MessageStatus = { senderName: data[0], content: data[1], sentTime: data[3] }
this.data.next(streamStatus);
});
}
还有一些额外的调用来指定应该向谁提供消息的客户端。所以在后端,是一些类来处理这个逻辑。最后,最接近这个问题的是以下用于发送数据的方法:
private async Task ExecuteRequest(Message message)
{
Console.WriteLine($"Activiy of hub");
object[] messageArgs = { message.SenderName, message.Content, message.GetFormattedSentTime() };
string[] connectionIds = _hubManager.GetAllConnectionAssignedToSpecificChat(message.ChatId);
IList<Task> tasks = new List<Task>();
Console.WriteLine($"Try to send message {message.Content}");
foreach(string connectionId in connectionIds)
{
tasks.Add(_hub.Clients.Client(connectionId).SendAsync(METHOD, messageArgs, cancellationToken: _token).ContinueWith((task) =>
{
if (task.IsFaulted)
{
Console.WriteLine($"Fault during executing task: {task.Exception?.Message ?? "exception"}");
}
else
{
Console.WriteLine($"Message: {message.Content} was sent to {connectionId}");
}
}));
}
await Task.WhenAll(tasks);
}
非常感谢任何帮助! 问候。
【问题讨论】:
标签: angular asp.net-core signalr