【发布时间】:2020-09-23 16:51:40
【问题描述】:
我在我的 react 本机应用程序中使用 signalR 用于发布后的 cmets。当我第一次尝试建立连接并对帖子发表评论时,出现错误:在连接传输之前无法发送。但在第一次之后,它工作顺利。
我尝试过库,例如 @aspnet/signalr 和 @microsoft/signalr。两个库都发生了同样的事情。在我看来,我的连接有问题。
由于我需要在我的应用程序的不同区域(例如 cmets、通知和消息)发出信号,因此我正在以这种方式创建连接。
import {HubConnectionBuilder, LogLevel} from '@aspnet/signalr';
var connection_count = 0;
export const connectionSignalR = async (endPoint, token) => {
return new Promise((resolve, reject) => {
let _hubConnection = new HubConnectionBuilder()
.withUrl(
`http://www.XXXXXXX.com/${endPoint}?access_token=${token}`,
)
.configureLogging(LogLevel.Debug)
.build();
const startConnection = async () => {
await _hubConnection.start();
console.log('[SignalR Connection State]:', _hubConnection.state);
if (_hubConnection.state === 1) {
connection_count = 0;
resolve(_hubConnection);
} else {
console.log('[Error with connection signalR]: ');
if (connection_count < 3) {
connection_count = connection_count + 1;
console.log('[Trying to connection again]:');
startConnection();
} else {
connection_count = 0;
reject('Error in connection');
}
}
};
startConnection();
});
};
这个函数返回连接实例,我正在做这样的进一步处理
import {connectionSignalR} from '@services';
connectionSignalR('Comments', Token)
.then(hubConnection => {
let data = {
UserId: 'XXX',
Comment: 'My first Comment',
PostId: 'XXXX',
};
hubConnection.invoke('AddCommentAsync', data).then(() => {
hubConnection.on('AddComment', res => {
console.log('[Response from add comment]', res);
});
});
})
.catch(error => {
Toast.show('Network error!', error);
});
【问题讨论】:
标签: javascript node.js react-native signalr signalr.client