Use socket. io in node. js to create namespace _ node. js

Source: Internet
Author: User
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:







Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.