【发布时间】:2020-11-23 10:44:19
【问题描述】:
我正在尝试使用 javascript 客户端连接到信号 R 集线器。似乎我可以连接,但立即断开连接。
一些日志:
2020-03-11T11:43:47.974Z] 调试:发送握手请求。 Utils.js:209 [2020-03-11T11:43:47.978Z] 信息:使用 HubProtocol 'json'。 home.component.ts:115 建立与信号 r 的连接时出错 错误:解析握手响应时出错:TypeError:“instanceof”的右侧不可调用 在 HubConnection.push../node_modules/@aspnet/signalr/dist/esm/HubConnection.js.HubConnection.processHandshakeResponse (HubConnection.js:372) 在 HubConnection.push../node_modules/@aspnet/signalr/dist/esm/HubConnection.js.HubConnection.processIncomingData (HubConnection.js:322) 在 WebSocketTransport.HubConnection.connection.onreceive (HubConnection.js:65) 在 WebSocket.webSocket.onmessage [as __zone_symbol__ON_PROPERTYmessage] (WebSocketTransport.js:107) 在 WebSocket.wrapFn (zone-evergreen.js:1191) 在 ZoneDelegate.invokeTask (zone-evergreen.js:391) 在 Object.onInvokeTask (core.js:30885) 在 ZoneDelegate.invokeTask (zone-evergreen.js:390) 在 Zone.runTask (zone-evergreen.js:168) 在 ZoneTask.invokeTask [作为调用] (zone-evergreen.js:465)
连接到 SinalR 集线器时出现上述错误。下面是我的客户端代码:
this.hubConnection = new HubConnectionBuilder()
.withUrl('http://localhost:5000/signalr', {
accessTokenFactory: () => localStorage.getItem('token')
})
.configureLogging(LogLevel.Debug)
.build();
this.hubConnection
.start()
.then( () => console.log(this.hubConnection.state))
.catch( error => console.log('Error establishing connection to signal r ', error));
this.hubConnection.on('TotalTrucks', trucks => {
console.log('HERE = ', trucks);
this.tucks = trucks;
});
请注意,我有一个后台服务每 1 分钟向所有连接的客户端发送消息:
public class OtcWorker : BackgroundService
{
private readonly IHubContext<OtcHub> _hubContext;
private IServiceScopeFactory ServiceScopeFactory { get; set; }
public OtcWorker(IHubContext<OtcHub> hubContext, IServiceScopeFactory serviceScopeFactory)
{
_hubContext = hubContext;
ServiceScopeFactory = serviceScopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<WeighbridgeDataContext>();
while (!stoppingToken.IsCancellationRequested)
{
var result = await context.ReceiptTransactions.ToListAsync();
await _hubContext.Clients.All.SendAsync("TotalTrucks", result.Count);
await Task.Delay(3600, stoppingToken);
}
}
}
}
【问题讨论】:
-
你使用的是什么 SignalR 客户端包?
-
我正在使用来自 NPM 的 @aspnet/signalr
-
那个包现在已经过时了。试试
@microsoft/signalr。 docs.microsoft.com/en-us/aspnet/core/signalr/… -
即使使用@microsoft/signalr 也会给我同样的错误。
-
您可以查看此 SignalR 演示,该演示实现了一个工作器,该工作器还向所有客户端发送数据。 github.com/Kiril1512/SignalRDemo