最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Socket.io, difference between socket.set() and socket property? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Feb 12, 2012 at 18:27 kniteknite 6,1716 gold badges40 silver badges56 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

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;
};

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.

发布评论

评论列表(0)

  1. 暂无评论