- Server socket.io的入口类,通过require可创建出来。一般代码里都将其实例命名为“io”或“server”,因此当我们看到代码里有这个两个变量,指的就是这个类:fa-thumbs-o-up:
- Namespace 实际上是同一个server的不同的分支,同一个客户端连接多个namespace实际上是公用一个connection (websocket连接)。
- Room 对于某个Namespace下面的分组。比如聊天的时候,不同的分组可以对应不同的Room。
- Socket 与客户端通信的类。属于某个特定的Namespace,并且绑定了一个Client来做数据交互,在Namespace的on的callback中,作为第一个参数传给用户。
- Client 表示一个链接,多个Socket可以公用一个Client来做通信。
This is what namespaces and rooms have in common (socket.io v0.9.8):
Both namespaces (io.of('/nsp')) and rooms (socket.join('room')) are created on the server side Multiple namespaces and multiple rooms share the same (WebSocket) connection The server will transmit messages over the wire only to those clients that connected to / joined a nsp / room, i.e. it's not just client-side filtering The differences:
namespaces are connected to by the client using io.connect(urlAndNsp) (the client will be added to that namespace only if it already exists on the server) rooms can be joined only on the server side (although creating an API on the server side to enable clients to join is straightforward) namespaces can be authorization protected authorization is not available with rooms, but custom authorization could be added to the aforementioned, easy-to-create API on the server, in case one is bent on using rooms rooms are part of a namespace (defaulting to the 'global' namespace) namespaces are always rooted in the global scope To not confuse the concept with the name (room or namespace), I'll use compartment to refer to the concept, and the other two names for the implementations of the concept. So if you
need per-compartment authorization, namespaces might be the easiest route to take if you want hierarchically layered compartments (2 layers max), use a namespace/room combo if your client-side app consists of different parts that (do not themselves care about compartments but) need to be separated from each other, use namespaces. An example for the latter would be a large client app where different modules, perhaps developed separately (e.g. third-party), each using socket.io independently, are being used in the same app and want to share a single network connection.
Not having actually benchmarked this, it seems to me if you just need simple compartments in your project to separate and group messages, either one is fine.