Answer the question
In order to leave comments, you need to log in
Why don't client receive node.js websocket server events?
Why don't messages come from the server to the client? I start the server both clients are connected. The client sees his messages that he sends, but the other does not see. Although the event occurs on the server. Why is the other client not receiving the server event?
Here is the server:
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const port =441;
var processRequest = function( req, res ) {
res.writeHead(200);
res.end("All glory to WebSockets!\n");
};
const app= https.createServer({
key: fs.readFileSync('../crt/private.key'),
cert: fs.readFileSync('../crt/domain_name.crt')
}, processRequest ).listen(port);
const server = new ws.Server({server:app});
server.on('connection', function(ws,req) {
ws.send(JSON.stringify({'connected':"HI"}));
console.log({'connected':"HI"});
ws.on('message', function(message) {
console.log('получено сообщение ' + message);
ws.send(JSON.stringify({'connected':message}));
});
ws.on('close', function() {
ws.send(JSON.stringify({'disconnect':"off"}));
console.log(JSON.stringify({'disconnect':"off"}));
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<input type="button" value="ok" onclick="add()">
<script>
var socket = new WebSocket('wss://site.ru:441');
//socket.onopen = () => setInterval(() => socket.send('ping'), 1000);
//socket.onclose = (event) => socket.onclose = (event) => console.log((event.wasClean) ? 'Disconnected' : 'Connection break: ' + (event.reason || event.code)); //
socket.onmessage=function(event){
console.log( JSON.parse(event.data) );
}
function add(){
socket.send("Привет")
}
</script>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question