Troubleshooting WordPress Plugin: Node.js, WebSockets, and WebRTC Integration on Live Server

19 Views Asked by At

I have developed a WordPress plugin that incorporates Node.js, WebSockets, and WebRTC for enabling voice and video calls between users. The plugin works seamlessly on my local WordPress setup. However, when I install the plugin on a live WordPress instance hosted on Cloudways and attempt to start the Node.js server using the command npm run start, the functionality breaks. ** Here are the key details: **

  • The Node.js server is set up to run on a specific port (e.g., 3000) for handling WebSockets and WebRTC communication.
  • The WordPress installation on the live server is hosted on Cloudways.

** Here is the complete code Client side webrtc.js**

`let localStream;
let localVideo;
let peerConnection;
let remoteVideo;
let serverConnection;
let uuid;

const peerConnectionConfig = {
  'iceServers': [
    {'urls': 'stun:stun.stunprotocol.org:3478'},
    {'urls': 'stun:stun.l.google.com:19302'},
  ]
};

async function pageReady() {
  uuid = createUUID();

  localVideo = document.getElementById('localVideo');
  remoteVideo = document.getElementById('remoteVideo');

  serverConnection = new WebSocket(`wss://${window.location.hostname}:3000`);
  serverConnection.onmessage = gotMessageFromServer;

  const constraints = {
    video: true,
    audio: true,
  };

  if(!navigator.mediaDevices.getUserMedia) {
    alert('Your browser does not support getUserMedia API');
    return;
  }

  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);

    localStream = stream;
    localVideo.srcObject = stream;
  } catch(error) {
    errorHandler(error);
  }
}

function start(isCaller) {
  peerConnection = new RTCPeerConnection(peerConnectionConfig);
  peerConnection.onicecandidate = gotIceCandidate;
  peerConnection.ontrack = gotRemoteStream;

  for(const track of localStream.getTracks()) {
    peerConnection.addTrack(track, localStream);
  }

  if(isCaller) {
    peerConnection.createOffer().then(createdDescription).catch(errorHandler);
  }
}

function gotMessageFromServer(message) {
  if(!peerConnection) start(false);

  const signal = JSON.parse(message.data);

  // Ignore messages from ourself
  if(signal.uuid == uuid) return;

  if(signal.sdp) {
    peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(() => {
      // Only create answers in response to offers
      if(signal.sdp.type !== 'offer') return;

      peerConnection.createAnswer().then(createdDescription).catch(errorHandler);
    }).catch(errorHandler);
  } else if(signal.ice) {
    peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
  }
}

function gotIceCandidate(event) {
console.log(event.candidate , "--candidate");
  if(event.candidate != null) {
    serverConnection.send(JSON.stringify({'ice': event.candidate, 'uuid': uuid}));
  }
}

function createdDescription(description) {
  console.log('got description');

  peerConnection.setLocalDescription(description).then(() => {
    serverConnection.send(JSON.stringify({'sdp': peerConnection.localDescription, 'uuid': uuid}));
  }).catch(errorHandler);
}

function gotRemoteStream(event) {
  console.log('got remote stream');
  remoteVideo.srcObject = event.streams[0];
}

function errorHandler(error) {
  console.log(error);
}

// Taken from http://stackoverflow.com/a/105074/515584
// Strictly speaking, it's not a real UUID, but it gets the job done here
function createUUID() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }

  return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}



**Server.js file code**

const HTTPS_PORT = 3000;

const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;

// Yes, TLS is required for WebRTC
const serverConfig = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
};

function main() {
  const httpsServer = startHttpsServer(serverConfig);
  startWebSocketServer(httpsServer);
  printHelp();
}

function startHttpsServer(serverConfig) {
 
  const handleRequest = (request, response) => {
    console.log(`request received: ${request.url}`);

    // Check if the request URL matches '/webrtc/call/'
    if (request.url === '/webrtc/call/') {
      response.writeHead(200, {'Content-Type': 'text/html'});
      response.end(fs.readFileSync('path/to/your/custom/page.html'));
    } else if (request.url === '/') {
      // Handle other requests as before
      response.writeHead(200, {'Content-Type': 'text/html'});
      response.end(fs.readFileSync('client/index.html'));
    } else if (request.url === '/webrtc.js') {
      response.writeHead(200, {'Content-Type': 'application/javascript'});
      response.end(fs.readFileSync('client/webrtc.js'));
    }
  };

  const httpsServer = https.createServer(serverConfig, handleRequest);
  httpsServer.listen(HTTPS_PORT, '0.0.0.0');
  return httpsServer;
}

function startWebSocketServer(httpsServer) {
  // Create a server for handling websocket calls
  const wss = new WebSocketServer({server: httpsServer});

  wss.on('connection', (ws) => {
    ws.on('message', (message) => {
      // Broadcast any received message to all clients
      console.log(`received: ${message}`);
      wss.broadcast(message);
    });
  });

  wss.broadcast = function(data) {
    this.clients.forEach((client) => {
      if(client.readyState === WebSocket.OPEN) {
        client.send(data, {binary: false});
      }
    });
  };
}

function printHelp() {
  console.log(`Server running. Visit https://randomly.chat:${HTTPS_PORT} in Firefox/Chrome/Safari.\n`);
  console.log('Please note the following:');
  console.log('  * Note the HTTPS in the URL; there is no HTTP -> HTTPS redirect.');
  console.log('  * You\'ll need to accept the invalid TLS certificate as it is self-signed.');
  console.log('  * Some browsers or OSs may not allow the webcam to be used by multiple pages at once. You may need to use two different browsers or machines.');
}

main();`

Issues and Observations:

  • The server starts without errors, but the communication between users doesn't work as expected.

  • The plugin involves real-time communication, and it appears that the WebSocket connections might be encountering issues on the live server.

  • when i hit the URL (https://randomly.chat:3000/) it Shows This site can’t be reached. ** Questions:**

  • Are there any specific considerations for running a Node.js server alongside a WordPress installation on Cloudways?

  • Could there be issues with WebSockets or WebRTC communication in a live server environment?

  • Any insights on debugging real-time communication issues in a WordPress plugin on a live server?

  • I would appreciate any guidance, suggestions, or troubleshooting steps to identify and resolve the issues with running my WordPress plugin on a live server. Thank you!

0

There are 0 best solutions below