Home  >  Article  >  Web Front-end  >  Advanced usage skills of Socket.IO in node.js_node.js

Advanced usage skills of Socket.IO in node.js_node.js

WBOY
WBOYOriginal
2016-05-16 16:31:581362browse

In the previous blog post Socket.IO, I briefly introduced the basic use of Socket.IO and created a simple chat room DEMO. Based on the introductory chapter, this article continues to explore the advanced usage of Socket.IO. This article will start with configuration, rooms, events, etc., and introduce some practical APIs and precautions in Socket.IO.

1. Configuration

Socket.IO provides 4 configuration APIs: io.configure, io.set, io.enable, io.disable. Among them, io.set sets a single item, and io.enable and io.disable are used to set a single item in Boolean configuration. io.configure allows you to configure different parameters for different production environments (such as devlopment, test, etc.). The following defines different configurations of Socket.IO in development and release environments:

Copy code 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 commonly used configuration items. For specific configuration parameters, please refer to the official WIKI

1).transports (default ['websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']): An array containing communication method types. Socket.IO supports a variety of ways to achieve online instant communication, such as websocket, polling, etc. This configuration allows you to choose alternative communication methods.
2).log level (default 3): The lowest level of log output, 0 is error, 1 is warn, 2 is info, 3 is debug, the default is to output all types of logs.
3).heartbeat interval (default 25 seconds): Heartbeat packet sending interval. The client needs to send a heartbeat packet to the server within this time period to maintain communication.

2. Room

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

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

Copy code The code is as follows:

//1. Broadcast an event to my room, and the submitter will be excluded (that is, the message will not be received)
io.sockets.on('connection', function (socket) {
//Note: Compared with the following, here is the event submission from the client's perspective
socket.broadcast.to('my room').emit('event_name', data);
}

///2. Broadcast an event to another room, and all clients in this room will receive the message
//Note: Compared with the above, here is the event submission from the server's 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 the room, you can also obtain room information through the following API.

Copy code The code is as follows:

//Get information about all rooms
//key is the room name, value is the socket ID array corresponding to the room name
io.sockets.manager.rooms

//Get the client in the particular room and return all socket instances in this room
io.sockets.clients('particular room')

//Get the room information entered by this socket through socket.id
io.sockets.manager.roomClients[socket.id]

3. Event

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

Server side events:

1).io.sockets.on('connection', function(socket) {}): Triggered after the socket connection is successful, used for initialization
socket.on('message', function(message, callback) {}): This event is triggered when the client transmits a message through socket.send. message is the transmitted message, and 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() {}): Triggered when the socket loses connection (including closing the browser, actively disconnecting, disconnecting, etc. any disconnection situation)

Client events:

1).connect: Connection successful
2).connecting: Connecting
3).disconnect: Disconnect
4).connect_failed:Connection failed
5).error: An error occurred and cannot be handled by other event types
6).message: Same as server-side message event
7).anything: Same as server-side anything event
8).reconnect_failed: Reconnect failed
9).reconnect: Successfully reconnected
10).reconnecting: Reconnecting

Here we need to mention the order in which the client socket initiates a connection. When connecting for the first time, the event triggering sequence is: connecting->connect; when the connection is lost, the event triggering sequence is: disconnect->reconnecting (possibly multiple times)->connecting->reconnect-> connect.

4. Authorization

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

2). Enter a room (very easy to use! It is equivalent to a namespace and 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 a message to a room (including the sender can receive the message) (this API belongs to io.sockets): io.sockets.in('another room name').emit('broadcast room message' );

5). Force the use of WebSocket communication: (client) socket.send('hi'), (server) use socket.on('message', function(data){}) to receive.

The introduction to the advanced usage of Socket.IO basically ends here. Personally, I feel that these basic APIs are sufficient for daily use, which also reflects Socket.IO's extremely simple and easy-to-use design philosophy. This article is just an introduction. When you encounter problems that cannot be solved in actual application, it would be better to check the official detailed WIKI.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn