简体   繁体   中英

How Can I Transfer This http Node.Js to run on https?

Recently i created a node js and webrtc project that use http. But I notified that webrtc only works with https. So how can i transfer this http based node js file to https based one? Please help me.

Really i have no idea how to do this. So please help me to make it. What is need is to run this file over https. Not in http. As you can see, the below code use just http. As the webrtc need to run over https, i just need to make this file to run over https too

var hat = require('hat')
var http = require('http')
var nodeStatic = require('node-static')
var ws = require('ws')

var PORT = process.argv[2] || 4000

var httpServer = http.createServer()
var staticServer = new nodeStatic.Server('./public')
var wsServer = new ws.Server({ server: httpServer })

var peers = {}
var waitingId = null
var count = 0

httpServer.on('request', function (req, res) {
  req.addListener('end', function () {
    staticServer.serve(req, res)
  }).resume()
})

wsServer.on('connection', onconnection)

function onconnection (peer) {
  var send = peer.send
  peer.send = function () {
    try {
      send.apply(peer, arguments)
    } catch (err) {}
  }

  peer.id = hat()
  peers[peer.id] = peer
  peer.on('close', onclose.bind(peer))
  peer.on('error', onclose.bind(peer))
  peer.on('message', onmessage.bind(peer))
  count += 1
  broadcast(JSON.stringify({ type: 'count', data: count }))
}

function onclose () {
  peers[this.id] = null
  if (this.id === waitingId) {
    waitingId = null
  }
  if (this.peerId) {
    var peer = peers[this.peerId]
    peer.peerId = null
    peer.send(JSON.stringify({ type: 'end' }), onsend)
  }
  count -= 1
  broadcast(JSON.stringify({ type: 'count', data: count }))
}

function onmessage (data) {
  console.log('[' + this.id + ' receive] ' + data + '\n')
  try {
    var message = JSON.parse(data)
  } catch (err) {
    console.error('Discarding non-JSON message: ' + err)
    return
  }

  if (message.type === 'peer') {
    if (waitingId && waitingId !== this.id) {
      var peer = peers[waitingId]

      this.peerId = peer.id
      peer.peerId = this.id

      this.send(JSON.stringify({
        type: 'peer',
        data: {
          initiator: true
        }
      }), onsend)

      peer.send(JSON.stringify({
        type: 'peer'
      }), onsend)

      waitingId = null
    } else {
      waitingId = this.id
    }
  } else if (message.type === 'signal') {
    if (!this.peerId) return console.error('unexpected `signal` message')
    var peer = peers[this.peerId]
    peer.send(JSON.stringify({ type: 'signal', data: message.data }))
  } else if (message.type === 'end') {
    if (!this.peerId) return console.error('unexpected `end` message')
    var peer = peers[this.peerId]
    peer.peerId = null
    this.peerId = null
    peer.send(JSON.stringify({ type: 'end' }), onsend)
  } else {
    console.error('unknown message `type` ' + message.type)
  }
}

function onsend (err) {
  if (err) console.error(err.stack || err.message || err)
}

function broadcast (message) {
  for (var id in peers) {
    var peer = peers[id]
    if (peer) {
      peer.send(message)
    }
  }
}

httpServer.listen(PORT, function () {
  console.log('Listening on port ' + PORT)
})
  1. Register a site domain for under $15.00/year (for.com) including whois protection.
  2. Create a free Cloudflare account and setup your new Domain Name, configure the DNS to proxy and handle your IPs you plan to host with under such domain.
  3. Generate through cloudflare SSL Key, and utilize the certs in your projects. As long as the DNS routes to say your home IP or server IP it'll maintain that HTTPS.

For testing purposes you can use fake key/cert but this will always show insecure until you follow the above steps.

In NodeJS to engage the HTTPS:

 const HTTPS = require('https'); const FILESYSTEM = require('fs'); // CREATE HTTP APP HERE THEN CREATE HTTPS SERVER FOR THE APP HTTPS.createServer({ key: FILESYSTEM.readFileSync(__dirname + '/certs/key.pem'), cert: FILESYSTEM.readFileSync(__dirname + '/certs/cert.pem') }, app).listen(443);

HTTPS requires a security certificate which matches the domain name. Both domain name and certificate for production usage can be purchased online and will have an expiration date and will need renewals.

The certificate comprises of two files cert.pem and key.pem .

For local development a self-signed untrusted certificate can be generated for localhost domain (via openssl command-line tool).

openssl req -x509 -nodes -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'

The original code can be updated from 'http' to 'https' and those two files need to be loaded and passed as options to https.createServer()

I also had to update the call to 'node-static' as it was not serving local files.

var hat = require('hat')
var https = require('https') // updated
const fs = require('fs');
var nodeStatic = require('node-static')
var ws = require('ws')

var PORT = process.argv[2] || 4000

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

var httpServer = https.createServer(options) // updated
var staticServer = new nodeStatic.Server('./public')
var wsServer = new ws.Server({ server: httpServer })

var peers = {}
var waitingId = null
var count = 0

httpServer.on('request', function (req, res) { // updated
  staticServer.serve(req, res)
})

// the rest of the original code
// httpServer variable is now an HTTPS server instance


httpServer.listen(PORT, function () {
  console.log('Listening on port ' + PORT)
})

Starting the server and visiting https://localhost:4000 will be prompted with untrusted certificate warning which you have to acknowledge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM