如果开发者想在一个特定的应用程序中完全控制消息与事件的发送,只需要使用一个默认的"/"命名空间就足够了.但是如果开发者需要将应用程序作为第三方服务提供给其他应用程序,则需要为一个用于与客户端连接的socket端口定义一个独立的命名空间.
io.of(namespace)
[b]制作两个命名空间[/b]
chat和news然后在客户端相互发送信息.
[url=http://localhost/chat]http://localhost/chat[/url]"),
news=io.connect("[url=http://localhost/news]http://localhost/news[/url]");
chat.on("connect", function () {
chat.send("你好.");
chat.on("message", function (msg) {
console.log("从char空间接收到消息:"+msg);
});
});
news.on("connect", function () {
news.emit("send message","hello");
news.on("send message", function (data) {
console.log("从news命名空间接收到send message事件,数据位:"+data);
});
});
</script>
</head>
<body>
</body>
</html>
运行结果:
[img]http://files.jb51.net/file_images/article/201412/2014121511522814.png[/img]
小伙伴们是否了解了在node.js中使用socket.io制作命名空间的方法了呢,这里的2个例子很简单,童鞋们自由发挥下。