node.js中使用socket.io制作命名空间
内容摘要
如果开发者想在一个特定的应用程序中完全控制消息与事件的发送,只需要使用一个默认的"/"命名空间就足够了.但是如果开发者需要将应用程序作为第三方服务提供给其他应用程序,
文章正文
如果开发者想在一个特定的应用程序中完全控制消息与事件的发送,只需要使用一个默认的"/"命名空间就足够了.但是如果开发者需要将应用程序作为第三方服务提供给其他应用程序,则需要为一个用于与客户端连接的socket端口定义一个独立的命名空间.
io.of(namespace)
制作两个命名空间
chat和news然后在客户端相互发送信息.
http://localhost/chat"),
news=io.connect("http://localhost/news");
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>
news=io.connect("http://localhost/news");
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>
运行结果:
小伙伴们是否了解了在node.js中使用socket.io制作命名空间的方法了呢,这里的2个例子很简单,童鞋们自由发挥下。
代码注释