Advanced Socket. IO usage tips in node. js _ node. js

Source: Internet
Author: User
Tags emit
This article mainly introduces node. socket. js. i/O advanced usage skills. This article describes the configuration, room, event, authorization, and other content. For more information, see Socket in the previous blog. IO, I briefly introduced Socket. i/O basic usage and a simple chat room DEMO is created. This article will continue to explore the advanced usage of Socket. IO Based on the introduction. This article introduces some APIs and precautions for using Socket. IO in terms of configuration, room, and event.

1. Configuration

Socket. IO provides four configuration APIs: io. configure, io. set, io. enable, io. disable. Io. set is used to set individual items. io. enable and io. disable are used to set Boolean configurations for individual items. Io. configure allows you to configure different parameters for different production environments (such as devlopment and test. The following defines the different configurations of Socket. IO in the development and release environments:

The Code is as follows:


Var io = require ('socket. io '). listen (80 );

Io. configure ('development', function (){
Io. enable ('browser client etag ');
Io. set ('Log level', 1 );
});

Io. configure ('release', function (){
Io. set ('transports ', ['websocket']);
});

The following lists some common configuration items. For specific configuration parameters, see the official WIKI.

1). transports (['websocket ', 'htmlfile', 'xhr-polling', 'jsonp-polling'] by default): An array containing the communication method type. Socket. IO supports multiple online instant communication methods, such as websocket and polling. This configuration allows you to select the alternate communication mode.
2). log level (default: 3): The lowest log output level. 0 indicates error, 1 indicates warn, 2 indicates info, and 3 indicates debug. By default, all types of logs are output.
3). heartbeat interval (25 seconds by default): The heartbeat packet sending interval. The client needs to send a heartbeat packet to the server during this time period to maintain communication.

2. Room

The room is a very useful function provided by Socket. IO. The room is equivalent to providing a namespace for some specified clients. All broadcasts and communication in the room will not affect clients outside the room.

In this article, we know that socket. join ('room name') can be used by the client to enter the room, and socket. leave ('room name') is used to leave the room. When the client enters a room, you can broadcast messages in the room in the following two ways:

The Code is as follows:


// 1. broadcast an event to my room. The submitter will be excluded (no message will be received)
Io. sockets. on ('connection', function (socket ){
// Note: In comparison with the following, the event is submitted from the client perspective.
Socket. broadcast. to ('My room '). emit ('event _ name', data );
}

// 2. broadcast an event to the another room. All clients in the room will receive a message
// Note: In comparison with the above, the event is submitted from the server perspective.
Io. sockets. in ('another room '). emit ('event _ name', data );

// Broadcast to all clients
Io. sockets. emit ('event _ name', data );

In addition to broadcasting messages to a room, you can use the following APIs to obtain room information.

The Code is as follows:


// Obtain information about all rooms
// The key is the room name, and the value is the socket ID array corresponding to the room name
Io. sockets. manager. rooms

// Obtain the client in the participant room and return all socket instances in the room
Io. sockets. clients ('particle room ')

// Use socket. id to obtain information about the room that the socket enters.
Io. sockets. manager. roomClients [socket. id]

3. Events

Socket. IO has some built-in default events. We should avoid the default event names when designing events and use these default events flexibly.

Server events:

1). io. sockets. on ('connection', function (socket) {}): triggered after the socket connection is successful and used for initialization
Socket. on ('message', function (message, callback) {}): the client uses socket. this event is triggered when sending a message. The message is the message to be transmitted, and the callback is the callback to be executed after receiving the message.
2). socket. on ('anything ', function (data) {}): triggered when any event is received
3). socket. on ('disconnect', function () {}): This is triggered when the socket loses connection (including closing the browser, actively disconnecting, or disconnecting)

Client events:

1). connect: Connection successful
2). connecting: connecting
3). disconnect: disconnect
4). connect_failed: Connection Failed
5). error: the error occurs and cannot be handled by other event types.
6). message: Same Server message event
7). anything: Same-server-side anything event
8). reconnect_failed: Reconnect failed
9). reconnect: reconnect successful
10). reconnecting: Re-connecting

Here we will mention the sequence in which the client socket initiates the connection. When a connection is established for the first time, the event trigger sequence is: connecting-> connect. When a connection is lost, the event trigger sequence is: disconnect-> reconnecting (which may be performed multiple times) -> connecting-> reconnect-> connect.

4. Authorization

1). broadcast to all clients: socket. broadcast. emit ('broadcast message ');

2). enter a room (very useful! It is equivalent to a namespace that can broadcast to a specific room without affecting clients in other rooms or not in the room): socket. join ('Your room name ');

3). broadcast a message to a room (the sender cannot receive the message): socket. broadcast. to ('Your room name'). emit ('broadcast room message ');

4 ). broadcast messages to a room (including messages received by the sender) (this API is io. sockets): io. sockets. in ('another room name '). emit ('broadcast room message ');

5 ). force WebSocket communication: (client) socket. send ('Hi'), (server) uses socket. on ('message', function (data.

The advanced usage of Socket. IO is basically here. I personally feel that these basic APIs are enough in daily use, which also reflects the extremely simple and easy-to-use design philosophy of Socket. IO. This article is just a reference. When you encounter problems that cannot be solved in practical use, it is better to go to the official WIKI.

Related Article

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.