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?
ws.sendwherewsis a parameter from a new connection. The send at bottom sends via some magic variablewsthat you never show how it's set. If you want to send more messages you need to keep the firstwsaround somewhere like add it to a list of connections or pass it to some class that will manage it etc...wsisnt any magic variable? Its set at line 8. Of course, I know this variable can only be used within it's scope.. And thats why im making this question. how do you pass ws outside its scope?ws undefinedornull not a function