node.js中使用socket.io製作命名空間_node.js

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.