如果開發人員想在一個特定的應用程式中完全控制訊息與事件的發送,只需要使用一個預設的"/"命名空間就足夠了.但是如果開發人員需要將應用程式作為第三方服務提供給其他應用程式,則需要為一個用於與用戶端串連的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.js中使用socket.io製作命名空間的方法了呢,這裡的2個例子很簡單,童鞋們自由發揮下。