Deploy nodejs websocket api to heroku

Viewed 68

I have a javascript file which implements a simple websocket. This websocket works on the localhost fine. But it is not running when I deploy the whole code to heroku. For localhost I am using : ws://localhost:<port> And after deploying to heroku, I am trying with : ws://<project-name>.herokuapp.com

Below is the code for the web.js file:

const express = require('express')
const app = express()
const port = process.env.PORT || 3000

const server = http.createServer((req, res) => {})

server.listen(port, ()=>{
  console.log("Listening on port ", port)
})

wsServer = new SocketServer({httpServer:server})

const connections = []

wsServer.on('request', (req)=>{
  const connection = req.accept()
  console.log('new connection')
  connections.push(connection)

  connection.on('message', (mes)=>{
    connections.forEach(element=>{
      if(element != connection){
        element.send(mes.utf8Data)
      }
    })
  })

  connection.on('close', (resCode, des)=>{
    console.log('connection closed')
    connections.splice(connections.indexOf(connection), 1)
  })
})

For the deployment I am using this command

git push heroku master

Later then, the deployment is successful with a https url returned on the console

https://<project-name>.herokuapp.com/ deployed to Heroku

And I am replacing the https with ws only (I think this might be the issue but not quite sure)

1 Answers

And I am replacing the https with ws only (I think this might be the issue but not quite sure)

Solution for the this problem is using wss instead of only ws.

Related