Node.js: websocket and express server shows unresolved server Problem
I am trying to install a new websocket server with an existing express server like this:
const http = require('http');
const express = require('express');
const app = express();
const port = 3000;
const bodyparser = require('body-parser');
const server = http.createServer(app);
const WebSocket = require('ws');
const wss = new WebSocket.Server({server:server});
wss.on('connection', function connection(ws) {
console.log('A new client Connected!');
ws.send('Welcome New Client!');
ws.on('message', function incoming(message) {
console.log('received: %s', message);
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
//routing
const roomsRoute = require('./Implementierung/Ressourcen/rooms');
app.get("https://stackoverflow.com/", (req, res) => {
res.send('Hear them');
});
server.listen(port, () => {
console.log(`listening on port ${port}`);
});
First, I got a problem with this line:
const wss = new WebSocket.Server({server:server});
I am not able to create a new WebSocket Server this way.
At second:
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
WebSocket.OPEN shows an error, maybe because of non-existing WebSocket?
Read more here: Source link