In my application, node js needed sending messages to the websocket. I decided to write a client websocket server. Here is an example:

var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); }); connection.on('close', function() { console.log('echo-protocol Connection Closed'); }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); }); client.connect('ws://192.168.0.180:8080/', 'echo-protocol'); 

How to send a message from an event handler where connect has already occurred, this is understandable, in this case connection.sendUTF for example. And how to send a message not through an event handler, I do not understand. I tried client.sendUTF, client.send and etc. - all to no avail ... When starting, it says that a function was not found. I tried to manually find the method, I did not find it, there is also no documentation. How to send a message not from the connect event handler?

  • What kind of implementation do you use? What is the use of sending messages outside the connection? - JK_Action

1 answer 1

The problem you have is that the client and connection are different objects (of different "classes"). To solve your problem, you need to somehow save the connection variable.

 var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); var _connection = null; client.on('connectFailed', function(error) { console.log('Connect Error: ' + error.toString()); }); client.on('connect', function(connection) { console.log('WebSocket Client Connected'); connection.on('error', function(error) { console.log("Connection Error: " + error.toString()); _connection = null; }); connection.on('close', function() { console.log('echo-protocol Connection Closed'); _connection = null; }); connection.on('message', function(message) { if (message.type === 'utf8') { console.log("Received: '" + message.utf8Data + "'"); } }); }); function Send(data){ if (_connection === null){ throw 'Not connect'; } _connection.send(data); //не ведаю какое у вас апи подставьте свой метод } client.connect('ws://192.168.0.180:8080/', 'echo-protocol'); 

There is one problem. In any case, you need to wait for the connection event in some way to start the exchange correctly. You can write some kind of controller and bind it.