socketio中的关于acknowledgement的进一步解释

websocket中对于消息的确认(acknowledgement)是没有实现的,需要我们自己在收到消息后回复一遍,如此增加了程序的复杂度。

socketio是对websocket的一些封装,提供了很多有价值的方法,其中就是确认(acknowledgement)的实现,非常棒的封装。

首先让我们来描述一下场景,然后从场景中知道一些定义:
1,网页发出一个websocket请求,发给服务器,服务器收到后,对网页来个确认消息。我们称网页为client,服务端为server。这个非常好理解。
2,服务器发一个websocket请求给网页,网页收到后,对服务器来个确认消息。我们还是称网页为client,服务端为server。这个也是容易理解的。

但是websocket非常特殊,因为服务器端能主动给网页端发消息,假如我们从消息的发送方(sender)和消息的接收方(receiver)来看,我们可以这么称消息的发送方为client,消息的接收方为server。那么从这个方面来看,当服务器端能主动给网页端发消息,服务器端为client,而网页端为server。

为了避免混淆,我们统统称网页端为client,服务器端为server。

我们来看一下 socketio 的文档:Sometimes, you might want to get a callback when the client confirmed the message reception. #有时候,在客户端发送消息后,客户端对服务端收到消息后,客户端需要有个回调来进行一些处理(确认)

下面这个例子就举了客户端发送消息给服务端,然后服务端对该消息进行了确认,这个确认能在客户端得到响应:


Server (app.js)
var io = require('socket.io')(80);

io.on('connection', function (socket) {
  socket.on('ferret', function (name, word, fn) {
    fn(name + ' says ' + word);
  });
});
--------------------------------------------------
Client (index.html)
<script>
  var socket = io(); // TIP: io() with no args does auto-discovery
  socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
    socket.emit('ferret', 'tobi', 'woot', function (data) { // args are sent in order to acknowledgement function
      console.log(data); // data will be 'tobi says woot'
    });
  });
</script>

socketio的文档关于acknowledgement只讲了上面这个例子,其实从websocket来看,还有服务端发消息给客户端,然后客户端进行确认,从而服务端能得到回调这样的流程。

所以,从上面2个流程的意义上来看,那么这句话改成如下的就更加能明白了:
Sometimes, you might want to get a callback when the sender confirmed the message reception.

嗯,最好的例子我找了个,写得非常好:
https://github.com/mrniko/netty-socketio-demo ,大家可以去看看
另外,http://www.cnblogs.com/lightsong/p/10226940.html, 这篇文章解释了确认(acknowledgement)的实现机理,感兴趣的同学可以去看看。

参考资料

socketio文档
netty-socketio例子
acknowledgement的实现机理