wangduanduan / wangduanduan.github.io

Wubba Lubba dub-dub
https://wdd.js.org
27 stars 7 forks source link

socket.io在socket对象上添加一些数据 #312

Closed wangduanduan closed 5 years ago

wangduanduan commented 5 years ago

socket.io: 2.2.0

socket.io官方例子,直接在socket对象上添加属性

// https://github.com/socketio/socket.io/blob/318d62/examples/chat/index.js#L36
 socket.username = username;
    // add the client's username to the global list
    usernames[username] = username;

避免冲突

为了避免冲突,你最好不要写一些和socket同名的属性

// https://github.com/socketio/socket.io/blob/318d62e5ad/lib/socket.js
function Socket(nsp, client){
  this.nsp = nsp;
  this.server = nsp.server;
  this.adapter = this.nsp.adapter;
  this.id = client.id;
  this.request = client.request;
  this.client = client;
  this.conn = client.conn;
  this.rooms = [];
  this.acks = {};
  this.connected = true;
  this.disconnected = false;
}

参考