node中的socket.io制作命名空间

时间:2023-03-09 08:44:31
node中的socket.io制作命名空间

如果开发者想在一个特定的应用程序中完全控制消息与事件的发送,只需要使用一个默认的"/"命名空间就足够了.但是如果开发者需要将应用程序作为第三方服务提供给其他应用程序,则需要为一个用于与客户端连接的socket端口定义一个独立的命名空间.

io.of(namespace)

制作两个命名空间

chat和news然后在客户端相互发送信息.

 var express=require("express");
var http=require("http");
var sio=require("socket.io");
var app=express();
var server=http.createServer(app);
app.get("/", function (req,res) {
res.sendfile(__dirname+"/index.html");
});
server.listen(1337,"127.0.0.1", function () {
console.log("开始监听1337");
});
var io=sio.listen(server);
var chart=io.of("/chat").on("connection", function (socket) {
socket.send("欢迎访问chat空间!");
socket.on("message", function (msg) {
console.log("chat命名空间接收到信息:"+msg);
});
});
var news=io.of("/news").on("connection", function (socket) {
socket.emit("send message","欢迎访问news空间!");
socket.on("send message", function (data) {
console.log("news命名空间接受到send message事件,数据为:"+data);
});
});
 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/socket.io/socket.io.js"></script>
<script>
var chat=io.connect("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>

运行结果:

node中的socket.io制作命名空间