socketio中的namespace

来源:互联网 发布:13米半挂车运费计算法 编辑:程序博客网 时间:2024/05/20 09:24

socketio中的namespace的概念。如果希望服务端发送的信息在所有客户端都能收到,那么使用默认的namespace / 就好了。但是如果想把发送信息的服务器作为第三方应用给不同客户端使用,就需要为每一个客户端定义一个namespace。先看以下代码。

服务端代码(index.js):

var express = require('express');var app = express();var http = require('http').Server(app);var io = require('socket.io')(http);app.use(express.static('./'));app.get('/', function(req, res){    res.sendFile(__dirname + '/index.html');});var chat = io  .of('/chat')  .on('connection', function(socket){    socket.emit('a message', {that: 'only', '/chat': 'will get'});  }); var news = io   .of('/news')   .on('connection', function(socket){    socket.emit('item', {news: 'item'});   });http.listen(3000, function(){    console.log('Listening on port 3000!');});

客户端代码(index.html):

<!DOCTYPE html><html>    <head>        <title>namespace</title>    </head>    <body>      <p>hello!</p>      <script src="/socket.io/socket.io.js"></script>        <script>            var chat = io.connect('http://localhost:3000/chat');            // var news = io.connect('http://localhost:3000/news');            chat.on('a message', function(data){                console.log(data);            });            // news.on('item', function(data){            //  console.log(data);            // })        </script>    </body></html>

在服务端,我们定义了两个namespace '/chat''/news' 。在客户端,我们只和namespace为 '/chat' 有连接,所以当socket连接上之后,只能收到在服务端namespace为 '/chat' 发送的信息,即 {that: 'only', '/chat': 'will get'}

1 0
原创粉丝点击