Search code examples
javascriptnode.jswebrtcpeerjs

socket.io connections failing after integrating peer server in my code


hi as you know public server is down so i tried to host my on peer server i already had a nodejs/express server up for chat ... so i tried to integrate peer server on my chat server

here is simplified version of my code

const  env = require('dotenv').config({ path: '.env' })
const express = require('express');
const { ExpressPeerServer } = require('peer');
const fs = require('fs');
const app = express();
const https = require('https');
const http = require('http');

let server ;

if(env.parsed.PROTOCOL === 'https')
{
    // server =  create https server
}
else
{
     server = http.createServer( app);
}


const { Server } = require("socket.io");
const io = new Server(server);

const peerServer = ExpressPeerServer(server, {
    debug: true
});
app.use('/peerjs', peerServer);


io.sockets.on('connection', function(socket) {
    console.log(`@ connection | socket -> ${socket.id} |`);
});


var PORT = env.parsed.PORT  || 8080

server.listen(PORT, () => {
    console.log(`listining to port ${PORT} `);
});

the problem is after adding peer server to my code i cant establish any socket.io connection to the server ... i get no errors in the server i just get the client side error

WebSocket connection to 'ws://localhost:8080/socket.io/?EIO=4&transport=websocket' failed: Invalid frame header

server is up and working , if i type localhost:8080 in the browser i will get the response

if i remove peer server code it would work fine

i can move peer server to separate code and run on a different port but i prefer to keep it in this code

any idea why this happening ?


Solution

  • According to this issue, it's not possible to run socket.io and a PeerJS server on the same Express(/http(s) server) instance.

    You should be able to start a separate PeerJS server from the same code file, as explained here:

    const { PeerServer } = require('peer');
    
    const peerServer = PeerServer({ port: 9000, path: '/myapp' });