Websocket第二条消息不发送?

时间:2015-09-01 17:48:56

标签: javascript websocket

我有一个websocket,我需要发送两条消息。看起来似乎没有收到第二条消息。我不确定这是我的代码或websocket本身的问题。我已经使用了Chrome Advanced Rest Tools客户端,并且能够成功发送这两封邮件,但我不确定为什么它在我的代码中无效。

var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
  console.log('i am open');
  ws.send(JSON.stringify(data1));
  //ws.send(JSON.stringify(data2));
  ws.emit('sendData2');
});
ws.on('sendData2', function sendBar() {
  console.log('testing!!');
  ws.send(JSON.stringify(data2));
});
ws.on('message', function message(msg1, msg1) {
  //the data received is a buffer
  console.log('received:', msg1, msg1);
  ws.close();
  done();
});

是否无法区分ws.on('message')中发送的不同数据?

1 个答案:

答案 0 :(得分:0)

我明白了。我需要添加一个if检查以确保我获得第一个数据,然后发送第二个数据。

var ws = new WebSocket('ws://localhost:15449/');
ws.on('open', function open() {
 console.log('i am open');
 ws.send(JSON.stringify(data1));
});
ws.on('message', function message(msg) {
  if(...) { 
    ws.send(JSON.stringify(data2));
  }
  console.log('received:', msg);
  ws.close();
  done();
});
相关问题