我正在使用我的SveltKit应用程序中的peerjs模块创建一个对等文件传输应用程序
此外,自定义信令服务器使用peerjs --port 5000
命令,并成功连接
这是我的文件发送者端的代码类型脚本:
import { FormatFileSize } from '../lib/utils/FormatFileSize'; // function to convert file size into a string of kb, MB, GB file sizes import Peer from 'peerjs'; import type { DataConnection } from 'peerjs'; // had to import separately because no export of DataConnection was shown from the 'peerjs' module I don't know why import { onMount } from 'svelte'; export let file: FileList; // the file which needs to be transfered let senderPeerId: string = ''; onMount(() => { let peer: Peer = new Peer({ host: '/', port: 5000 }); peer.on('open', function (id) { console.log('My peer ID is: ' + id); senderPeerId = id; }); peer.on('connection', (dataConnection: DataConnection) => { console.log('connected', dataConnection); dataConnection.send('Hello'); // trying to send this but it's not being recie dataConnection.on('data', function (data) { console.log('Received', data); // I am logging the data received from the other end }); }); });
这是我在文件接收方端的代码类型脚本(但这一端正在启动对等连接):
import type { PageData } from './$types'; import Peer from 'peerjs'; import { onMount } from 'svelte'; export let data: PageData; // in the formate of { receiverId: string } because this page params contain the peer id of the sender. let peer: Peer; // initiating here so that can use it elsewhere onMount(() => { peer = new Peer({ host: '/', port: 5000 }); peer.on('open', function (id) { console.log('My peer ID is: ' + id); startPeerConnection(); }); }); function startPeerConnection() { const dataConnection = peer.connect(data.receiverId); console.log(dataConnection); dataConnection.on('open', function () { console.log('connection started'); dataConnection.on('data', function (data) { console.log('Received', data); // logging the data, but no data is recieved }); dataConnection.send('World'); // this data is sent successfully and logged in the console of the other side }); }
我在这里做错了什么,或者只有发起连接的一方可以发送数据?
我浏览了互联网,但找不到类似的问题和解决方法,请帮助!!