This article mainly introduces how to use socket in node. for more information about how to create a namespace for I/O, see. If a developer wants to completely control the sending of messages and events in a specific application, you 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.
The 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 );
});
});
The Code is as follows: