How to send an image using peerjs, and display it in different computers?

时间:2019-04-08 13:46:23

标签: javascript html peerjs

With a few documentations, and some projects that I have found, I tried this program below, the goal is to be able to load an image from an input to display it on my screen, and to also display on the screen other users who will receive this same image. And also if someone can show me how to execute this code step by step knowing that I am new with peerjs. Thank's for any help :)

HTML file :

<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/peerjs/0.3.16/peer.min.js"></script>
  <script src="sender.js"></script>
</head>

<body>
  <form>
    <input type="file" />
  </form>
</body>
<div>
</div>

</html>

Javascript file :

document.addEventListener('DOMContentLoaded', event => {
  const peer = new Peer('sender', { host: 'localhost', port: 8080, path: '/' })

  const peer = new Peer('receiver', {
    host: 'localhost',
    port: 8080,
    path: '/'
  })

  peer.on('connection', conn => {
    conn.on('data', data => {
      if (data.filetype.includes('image')) {
        const bytes = new Uint8Array(data.file)
        const img = document.createElement('img')
        img.src = 'data:image/png;base64,' + encode(bytes)
        document.querySelector('div').prepend(img)
      }
    })
  })

  const conn = peer.connect('receiver')

  document.querySelector('input').onchange = function(event) {
    const file = event.target.files[0]
    const blob = new Blob(event.target.files, { type: file.type })

    conn.send({
      file: blob,
      filename: file.name,
      filetype: file.type
    })
  }
})

const encode = input => {
  const keyStr =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let output = ''
  let chr1, chr2, chr3, enc1, enc2, enc3, enc4
  let i = 0

  while (i < input.length) {
    chr1 = input[i++]
    chr2 = i < input.length ? input[i++] : Number.NaN // Not sure if the index
    chr3 = i < input.length ? input[i++] : Number.NaN // checks are needed here

    enc1 = chr1 >> 2
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
    enc4 = chr3 & 63

    if (isNaN(chr2)) {
      enc3 = enc4 = 64
    } else if (isNaN(chr3)) {
      enc4 = 64
    }
    output +=
      keyStr.charAt(enc1) +
      keyStr.charAt(enc2) +
      keyStr.charAt(enc3) +
      keyStr.charAt(enc4)
  }
  return output
}

I expect to display an image in every peer connected to the server

0 个答案:

没有答案
相关问题