我在simple-peer库的帮助下编写了一小段代码:
function App() {
const [receivingCall, setReceivingCall] = useState()
const [selfSingal, setSelfSingal] = useState()
function callIt(){
const peer = new Peer({
initiator: true,
trickle: false,
})
peer.on('signal', (data) => {
setSelfSingal(JSON.stringify(data))
})
peer.on('connect', () => {
console.log('I am connected now')
})
}
function answerIt(){
const peer = new Peer({
initiator: false,
trickle: false,
})
peer.on('signal', (data) => {
setSelfSingal(JSON.stringify(data))
})
peer.signal(receivingCall)
peer.on('data', data => {
// got a data channel message
console.log('got a message from peer1: ' + data)
})
peer.on('error', (err) => {
console.log('err', err)
})
peer.on('connect', () => {
console.log('connected!')
peer.send('hey peer2, how is it going?')
})
}
return (
<div className="App">
<div className="video">
<p><textarea name="1" id="1" cols="30" rows="10" onChange={(x)=> setSelfSingal(x.currentTarget.value)} value={selfSingal} /></p>
<button onClick={callIt}>connect 1</button>
<p><textarea name="2" onChange={(x)=> setReceivingCall(x.currentTarget.value)} id="2" cols="30" rows="10" value={receivingCall} /></p>
<button onClick={answerIt}>connect 2</button>
</div>
单击connect 1
按钮后,我会收到一个object
可以粘贴到第二个的按钮textarea
。通过这样做,我得到"type":"answer"
了回报,根据文档,这意味着我已连接。但是peer.on('connect'
没有触发,我不知道如何将任何数据发送到其他对等方。
peer.on('connect'
如果未触发,我如何确保我已连接到其他对等方并发送数据?