若是開發者想在一個特定的應用程序中徹底控制消息與事件的發送,只須要使用一個默認的"/"命名空間就足夠了.可是若是開發者須要將應用程序做爲第三方服務提供給其餘應用程序,則須要爲一個用於與客戶端鏈接的socket端口定義一個獨立的命名空間.html
io.of(namespace)express
製做兩個命名空間app
chat和news而後在客戶端相互發送信息.socket
1 var express=require("express"); 2 var http=require("http"); 3 var sio=require("socket.io"); 4 var app=express(); 5 var server=http.createServer(app); 6 app.get("/", function (req,res) { 7 res.sendfile(__dirname+"/index.html"); 8 }); 9 server.listen(1337,"127.0.0.1", function () { 10 console.log("開始監聽1337"); 11 }); 12 var io=sio.listen(server); 13 var chart=io.of("/chat").on("connection", function (socket) { 14 socket.send("歡迎訪問chat空間!"); 15 socket.on("message", function (msg) { 16 console.log("chat命名空間接收到信息:"+msg); 17 }); 18 }); 19 var news=io.of("/news").on("connection", function (socket) { 20 socket.emit("send message","歡迎訪問news空間!"); 21 socket.on("send message", function (data) { 22 console.log("news命名空間接受到send message事件,數據爲:"+data); 23 }); 24 });
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="/socket.io/socket.io.js"></script> 7 <script> 8 var chat=io.connect("http://localhost/chat"), 9 news=io.connect("http://localhost/news"); 10 11 chat.on("connect", function () { 12 chat.send("你好."); 13 chat.on("message", function (msg) { 14 console.log("從char空間接收到消息:"+msg); 15 }); 16 }); 17 news.on("connect", function () { 18 news.emit("send message","hello"); 19 news.on("send message", function (data) { 20 console.log("從news命名空間接收到send message事件,數據位:"+data); 21 }); 22 }); 23 </script> 24 </head> 25 <body> 26 27 </body> 28 </html>
運行結果:ui