Use socket. io in node. js to create a namespace.
If developers want to completely control the sending of messages and events in a specific application, they only need to use a default "/" namespace. however, if developers need to provide applications to other applications as third-party services, they need to define an independent namespace for a socket port used to connect to the client.
Io. of (namespace)
Create two namespaces
Chat and news then send messages to each other on the client.
Copy codeThe Code is as follows:
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 ("Start listening 1337 ");
});
Var io = sio. listen (server );
Var chart = io. of ("/chat"). on ("connection", function (socket ){
Socket. send ("Welcome to chat space! ");
Socket. on ("message", function (msg ){
Console. log ("message received by the chat namespace:" + msg );
});
});
Var news = io. of ("/news"). on ("connection", function (socket ){
Socket. emit ("send message", "Welcome to the news space! ");
Socket. on ("send message", function (data ){
Console. log ("The news namespace receives the send message event, and the data is:" + data );
});
});
Copy codeThe Code is as follows:
<! 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 ("hello .");
Chat. on ("message", function (msg ){
Console. log ("receive messages from char space:" + msg );
});
});
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 bit:" + data );
});
});
</Script>
</Head>
<Body>
</Body>
</Html>
Running result:
Do you know how to use socket. io to create a namespace in node. js? The two examples here are very simple.