Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用 PeerjsTransporter 时,控制台报错 #4

Open
TOmANDJerryz opened this issue Jul 17, 2020 · 3 comments
Open

使用 PeerjsTransporter 时,控制台报错 #4

TOmANDJerryz opened this issue Jul 17, 2020 · 3 comments

Comments

@TOmANDJerryz
Copy link

image

@lbaozi
Copy link

lbaozi commented Sep 16, 2020

我也遇到这个问题,打开了peerjs的debug看到是由于包太大导致的,对于大页面初始包会比较大,可以简单的自己实现一个peerjs的传输在发送时将发送的数据分片,接收的时候重新拼装

@TOmANDJerryz
Copy link
Author

我也遇到这个问题,打开了peerjs的debug看到是由于包太大导致的,对于大页面初始包会比较大,可以简单的自己实现一个peerjs的传输在发送时将发送的数据分片,接收的时候重新拼装

这个问题你解决了吗?

@lbaozi
Copy link

lbaozi commented Sep 16, 2020

我也遇到这个问题,打开了peerjs的debug看到是由于包太大导致的,对于大页面初始包会比较大,可以简单的自己实现一个peerjs的传输在发送时将发送的数据分片,接收的时候重新拼装

这个问题你解决了吗?

解决了,因为我只是做一个demo所以在发送的时候将数据进行了简单的拆分

async send<T>(data: T) {
  if (!this.conn) {
    await this.connect();
  }
  while (this.role === 'embed' && !this.opened) {
    // a spin lock to wait connection open
    await sleep(50);
  }
  let dataStr = JSON.stringify(data);
  const MAX_LENGTH = 200000;
  if (dataStr.length > MAX_LENGTH) {
    const count = Math.ceil(dataStr.length / MAX_LENGTH);
    for (let i = 0; i < count; i++) {
      const sendData = dataStr.slice(0, Math.min(dataStr.length, MAX_LENGTH));
      dataStr = dataStr.slice(Math.min(dataStr.length, MAX_LENGTH));

      this.conn?.send(`part${i + 1}-${count}endpart;${sendData}`);
    }
  } else {
    this.conn?.send(data);
  }
}

然后在接收的地方重新组装

conn.on('data', data => {
  data = this.joinData(data);
  if (!data) return;
  const { event, payload } = data;
  this.handlers[event as TransporterEvents].map(h =>
    h({
      event: event,
      payload: payload,
    })
  );
});
joinData (data:any) {
  if (typeof data === 'string' && data.startsWith('part') && data.includes('endpart;')) {
    const partData = data.split('endpart;');
    const index = parseInt(partData[0].split('-')[0].replace('part', ''), 10);
    const count = parseInt(partData[0].split('-')[1], 10);
    this.temp[index - 1] = partData[1];
    this.tempLength = this.tempLength + 1;
    console.log(`收到了拆包,当前包${index},共计:${count},已接收:${this.temp.length}`)

    if (this.tempLength !== count) return
      data = JSON.parse(this.temp.join(''));
      this.temp = [];
      this.tempLength = 0;
  }
  return data;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants