If a developer wants to fully control the sending of messages and events in a particular application, it is sufficient to use only a default "/" namespace. But if the developer needs to make the application available to other applications as a third-party service, You need to define a separate namespace for a socket port that is used to connect to the client.
Io.of (namespace)
Make two namespaces
Chat and news then send messages to each other on the client.
1 varExpress=require ("Express");2 varHttp=require ("http");3 varSio=require ("Socket.io");4 varapp=Express ();5 varServer=Http.createserver (app);6App.get ("/",function(req,res) {7Res.sendfile (__dirname+ "/index.html");8 });9Server.listen (1337, "127.0.0.1",function () {TenConsole.log ("Start listening 1337"); One }); A vario=Sio.listen (server); - varChart=io.of ("/chat"). On ("Connection",function(socket) { -Socket.send ("Welcome to chat space!")); theSocket.on ("message",function(msg) { -Console.log ("Chat namespace received message:" +msg); - }); - }); + varNews=io.of ("/news"). On ("Connection",function(socket) { -Socket.emit ("Send Message", "Welcome to News space!")); +Socket.on ("Send Message",function(data) { AConsole.log (the "News namespace accepts the Send Message event, the data is:" +data); at }); -});
1 <!DOCTYPE HTML>2 <HTML>3 <HeadLang= "en">4 <MetaCharSet= "UTF-8">5 <title></title>6 <Scriptsrc= "/socket.io/socket.io.js"></Script>7 <Script>8 varChat=Io.connect ("Http://localhost/chat"),9 News=Io.connect ("http://localhost/news");Ten One Chat.on ("Connect", function () { A Chat.send ("Hello , sir."); - Chat.on ("message", function(msg) { - Console.log ("receive a message from the Char space:"+msg); the }); - }); - News.on ("Connect", function () { - News.emit ("Send Message","Hello"); + News.on ("Send Message", function(data) { - Console.log ("receive the Send message event from the news namespace, data bits:"+data); + }); A }); at </Script> - </Head> - <Body> - - </Body> - </HTML>
Operation Result:
Socket.io in node making namespaces