If a developer wants to fully control the sending of messages and events in a specific application, it is sufficient to use a default "/" namespace. However, if the developer needs to provide the application as a third-party service to other applications, he or she needs to define a separate namespace for a socket port used to connect to the client.
io.of(namespace)
Make two namespaces
chat and news then send information to each other on the client side.
The code copy 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("chat namespace received information:"+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("news namespace accepts the send message event, the data is: "+data);
});
});
The code copy 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 message from char space:"+msg);
});
});
news.on("connect", function () {
news.emit("send message","hello");
news.on("send message", function (data) {
console.log("Receive send message event from the news namespace, data bit:"+data);
});
});
</script>
</head>
<body>
</body>
</html>
Running results:
Have you understood the method of using socket.io to create namespaces in node.js? The two examples here are very simple, so let’s play with them freely.