1

I am using the "ws" NodeJS websocket library. Previously I was trying out socket.io; with socket.io I could implement callbacks between the client and server like this:

socket.emit('Data', data, function(data){
       console.log(data);
});

socket.on('Data', function(data, callback){
       callback('it worked');
});

I have tried to do the same thing using the ws library, but have not had any success. Is it possible, and if so how?

2 Answers2

3

The API is pretty similar and you can do pretty much the same things.

For example on the server side instead of:

s.emit('message', 'message from server');

you use:

s.send('message from server', ()=>{});

To receive it on the client side instead of:

s.on('message', function (m) {
  // ...
});

you use:

s.addEventListener('message', function (m) {
  // ...
});

And so on.

In this answer I showed example code (both frontend and backend) to demonstrate the difference between Socket.io and WebSocket:

This is example server code:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Example browser code:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

See this for more info.

Community
  • 1
  • 1
rsp
  • 107,747
  • 29
  • 201
  • 177
0

This can be done with WebSockets-Callback like this

wscb.send({cmd: 'Hello server!'},
    function(response){
        //do something...
    }
)
vaid
  • 1,390
  • 12
  • 33