简体   繁体   English

NodeJS Websocket(ws)回调

[英]NodeJS Websocket (ws) Callback

I am using the "ws" NodeJS websocket library. 我正在使用“ ws” NodeJS websocket库。 Previously I was trying out socket.io; 以前我尝试过socket.io; with socket.io I could implement callbacks between the client and server like this: 使用socket.io我可以在客户端和服务器之间实现回调,如下所示:

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. 我尝试使用ws库执行相同的操作,但未成功。 Is it possible, and if so how? 有可能吗?

The API is pretty similar and you can do pretty much the same things. 该API非常相似,您可以做几乎相同的事情。

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: 在此答案中,我显示了示例代码(前端和后端)来演示Socket.io和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. 请参阅以获取更多信息。

This can be done with WebSockets-Callback like this 可以像这样通过WebSockets-Callback完成

wscb.send({cmd: 'Hello server!'},
    function(response){
        //do something...
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM