我对SignalR
中的关闭事件感到困惑。显然,有人称它为什么。 onClosed()
,closed()
等
在客户端的SignalR
侦听器中,我正在尝试实现此事件,但始终收到错误消息,指出它不是函数。我尝试了onClosed()
和closed()
。同样的错误。如何在客户端检测关闭事件?
const signalRListener = () => {
connection.on('new_message', message => {
// Handle incoming message.
// This is working fine.
})
connection.closed(e => {
// Try to restart connection but I never get here to due error I'm receiving
})
}
我在做什么错了?
这是我开始建立连接的方式:
export const signalRStart = (token) => {
connection = new signalR.HubConnectionBuilder()
.withUrl("/chat?access_token=" + token)
.configureLogging(signalR.LogLevel.Information)
.build();
// Set connection time out
connection.serverTimeoutInMilliseconds = 30000;
// Start connection
connection.start();
// Invoke listener
signalRListener();
}
答案 0 :(得分:4)
最佳做法是,在
connection.start
之后调用connection.on
,以便在接收到任何消息之前先注册您的处理程序。
export const signalRStart = (token) => {
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chat?access_token=" + token)
.configureLogging(signalR.LogLevel.Information)
.build();
// Set connection time out
connection.serverTimeoutInMilliseconds = 30000;
//register listeners
//Registers a handler that will be invoked when the hub method with the specified method name is invoked.
connection.on('new_message', message => {
// Handle incoming message.
// This is working fine.
});
//Registers a handler that will be invoked when the connection is closed.
connection.onclose(e => {
// ...
});
// Start connection
connection.start();
};