In my previous blog post, Socket.IO, I briefly introduced the basic usage 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 from 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. io.set sets the single item, and io.enable and io.disable are used to set the Boolean configuration in single item. io.configure allows you to configure different parameters for different production environments (such as development, test, etc.). The following defines the different configurations of Socket.IO in two environments:
The code copy 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 realize instant online communication, such as websocket, polling, etc. This configuration allows you to choose the backup communication method yourself.
2).log level (default 3): The lowest level of log output, 0 is error, 1 is warn, 2 is info, and 3 is debug, and all types of logs are output by default.
3).heartbeat interval (default 25 seconds): The 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 feature provided by Socket.IO. The room is equivalent to providing a namespace for some specified clients, and all broadcasts and communications in the room will not affect clients outside the room.
In the introduction, we know that socket.join('room name') can be used to enter the room by client, and socket.leave('room name') is used to leave the room. When the client enters a room, the message can be broadcasted in the room in two ways:
The code copy is as follows:
//1. Broadcast an event to my room, and the submitter will be excluded (that is, no message will be received)
io.sockets.on('connection', function (socket) {
//Note: Compared with the following, here is to submit events 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 a message
//Note: Compared with the above, here is to submit events 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.
The code copy 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 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. Events
Socket.IO has some built-in default events. When designing events, we should avoid the default event names and flexibly use these default events.
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. The message is the transmitted message. Callback is the callback to be executed after receiving the message.
2).socket.on('anything', function(data) {}): fired when any event is received
3).socket.on('disconnect', function() {}): triggers when the socket loses connection (including any disconnection situations such as closing the browser, actively disconnecting, disconnecting, etc.)
Client Events:
1).connect: The connection is successful
2).connecting: Connecting
3).disconnect: Disconnect
4).connect_failed: Connection failed
5).error: An error occurred and cannot be processed by other event types.
6).message: The same server-side message event
7).anything: anything event on the same server
8).reconnect_failed: Reconnect failed
9).reconnect: Successfully reconnected
10).reconnecting: Reconnecting
Here we need to mention the order when the client socket initiates the connection. When the first connection is connected, the event triggering order is: connect->connect; when the connection is lost, the event triggering order is: disconnect->reconnecting (may be performed multiple times)->connecting->reconnect->connect->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, which can be broadcast to a specific room without affecting clients in other rooms or not in the room): socket.join('your room name');
3). Broadcast 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 sender can receive messages) (this API belongs to io.sockets): io.sockets.in('another room name').emit('broadcast room message');
5). Force WebSocket communication: (client) socket.send('hi'), (server) use socket.on('message', function(data){}) to receive.
This is basically the introduction to the advanced usage of Socket.IO. I personally feel that these basic APIs are enough in daily use, which also reflects Socket.IO's extremely simple and easy-to-use design philosophy. This article is just a way to attract attention. When encountering problems that cannot be solved in actual use, it will be better to check the official detailed WIKI.