【问题标题】:Error: Cannot send until the transport is connected - SignalR错误:在连接传输之前无法发送 - SignalR
【发布时间】: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


    【解决方案1】:

    首先你应该使用@microsoft/signalr 包,因为另一个已经过时了,这是维护和接收更新的包。

    关于您的错误:您应该在开始连接之前注册监听器。所以在搭建hub的时候需要注册这行代码。

    hubConnection.on('AddComment', res => {
            console.log('[Response from add comment]', res);
          });
    

    所以应该是这样的:

    let _hubConnection = new HubConnectionBuilder()
          .withUrl(
            `http://www.XXXXXXX.com/${endPoint}?access_token=${token}`,
          )
          .configureLogging(LogLevel.Debug)
          .build();
    
    hubConnection.on('AddComment', res => {
            console.log('[Response from add comment]', res);
          });
    

    【讨论】:

    • 感谢您的回答。问题解决了。开始连接后我正在注册监听器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多