Socket.io, difference between socket.set() and socket property?

半腔热情 提交于 2020-01-12 06:53:30

问题


Socket.io recommends settings per-socket variables like so:

socket.set('foo', bar, function () {});

Variables can also be set and accessed on the socket:

socket.foo = bar

Is there a benefit to using the provided set() function?


回答1:


Calling socket.foo sets your property on the socket object itself. This isn't recommended because you could be overriding an internal property that socket uses and depends upon. When you call socket.set() this is stored in an internal data structure that won't clash with internal properties.

https://github.com/LearnBoost/socket.io/blob/master/lib/socket.js#L246

Socket.prototype.set = function (key, value, fn) {
  this.store.set(key, value, fn);
  return this;
};



回答2:


I believe the primary reason is so the data attached to the socket is multi-process safe.

If you're app is single process, always will be single process, and you're sure you're not overriding an internal attribute, socket.foo = bar will be fine. It would still be best to use get/set as a matter of future-proofing and best-practices.

In a multi-process world, if you set socket.foo = bar in one process, then in another process socket.foo will be undefined.



来源:https://stackoverflow.com/questions/9251407/socket-io-difference-between-socket-set-and-socket-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!