keanu_reeves
keanu_reeves

Reputation: 370

Send a message using websockets in node.js

hell0 there!

Today I tried to send a websocket message. What am I doing wrong? I commented the code bellow so hopefully you guys can understand my goal...

// Import websocket
const websocket = require('ws');

// Create server
var socket = new websocket.Server({ port: 8080 })

// When client connects to websock server, reply with a hello world message
socket.on('connection', ws => {
    ws.send('{"message":"Hello world."}'); //This works.
});

function send_message(msg){
    ws.send(msg);
}

/* Calculate something, await for user interaction, etc... */

// When im done with all that, just send a message.
send_message('{"message":"please work"}'); // This does not work

What am I doing wrong?

Upvotes: 0

Views: 1635

Answers (2)

user128511
user128511

Reputation:

You need to keep track of the connections. How you do that is up to you

const websocket = require('ws');

const socket = new websocket.Server({ port: 8080 })

const connections = [];
socket.on('connection', ws => {
    connections.push(ws);
});

// send a new message to every connection once per second
setInterval(() => {
  const date = new Date();
  for (const ws of connections) {
    ws.send(`hello again: ${date}`);
  }
}, 1000);

Of course a real app would probably track the connections via something more complicated than just an array of connections. It would also need to stop tracking those connections when they disconnect etc...

Upvotes: 2

Roy Chong
Roy Chong

Reputation: 35

const socket = new WebSocket('server_url'); // Connection opened 
socket.addEventListener('message', function (event) { socket.send('send message'); });

I used the WebSocket like this to send the message.

I hope this will help you to fix the issues.

Upvotes: 0

Related Questions