I took a game that my friend made and wanted to make it playable across browsers by sending keypress data between peers with WebRTC and websockets. However, I get this error
The confusion starts here:
const server = express();
The express
function doesn't really return a server, it returns an application. Commonly, the variable used for this is app
, but that's of course nothing more than convention (i.e. not a requirement).
However, it becomes an issue when you pass the app to the WS server:
const wss = new SocketServer({ server });
That's because SocketServer
requires an HTTP server instance, which server
is not.
Here's a fix, without renaming your variables:
let httpServer = server.listen(PORT, () => console.log(`Listening on ${ PORT }`));
...
const wss = new SocketServer({ server : httpServer });
(because when you call .listen()
on the Express instance, it will return an HTTP server instance)
Using the variable naming convention it would be this:
const app = express();
app.use(express.static(path.join(__dirname, 'lib')));
app.use('/assets', express.static(path.join(__dirname, 'assets')));
let server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const wss = new SocketServer({ server });