S
S
SergOdinokiy2019-11-12 08:58:06
Node.js
SergOdinokiy, 2019-11-12 08:58:06

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?
88iSy.jpg
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"}));


    });

});

Here is the client:
<!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>

Everything seems to be simple and should work. What could be the problem why the other client is not receiving server events?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2019-11-12
@SergOdinokiy

https://www.npmjs.com/package/ws#server-broadcast

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question