1. Introduction
First of all, the official website of Socket.IO: http://socket.io
The official website is very concise, and there is even no API documentation, only a simple "How to use" to refer to. Because Socket.IO is as simple and easy to use as the official website.
So what is Socket.IO? Socket.IO is a WebSocket library that includes client-side js and server-side nodejs. Its goal is to build real-time applications that can be used on different browsers and mobile devices. It will automatically choose the best way to realize real-time network application based on the browser from various methods such as WebSocket, AJAX long polling, Iframe streaming, etc., which is very convenient and user-friendly. The supported browsers are as low as IE5.5, which should meet most needs.
2. Installation and deployment
2.1 Installation
First of all, the installation is very simple, in the node.js environment, just one sentence:
The code copy is as follows:
npm install socket.io
2.2 Combining Express to build a server
express is a small Node.js web application framework, which is often used when building HTTP servers, so it is directly explained with Socket.IO and express as examples.
The code copy is as follows:
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(3001);
If you do not use express, please refer to socket.io/#how-to-use
3. Basic usage method
It is mainly divided into two pieces of code: server-side and client-side, both of which are very simple.
Server (app.js):
The code copy is as follows:
//Connect the above code
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('other event', function (data) {
console.log(data);
});
});
First, the io.sockets.on function accepts the string "connection" as the event in which the client initiates the connection. When the connection is successful, the callback function with socket parameters is called. When we use socket.IO, we basically handle user requests in this callback function.
The most important thing about socket is emit and on. The former submits (issues) an event (the event name is represented by a string). The event name can be customized, and there are some default event names, followed by an object, indicating the content sent to the socket; the latter receives an event (the event name is represented by a string), followed by a callback function that receives the event call, where data is the received data.
In the above example, we sent the news event and received the other event event, so the client should have corresponding receive and send events. Yes, the client code is exactly the opposite and very similar to the server.
Client(client.js)
The code copy is as follows:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('other event', { my: 'data' });
});
</script>
There are two things to note: the socket.io.js path needs to be written correctly. This js file is actually placed in the node_modules folder on the server side. It will be redirected when requesting this file. Therefore, don't be surprised that this file does not exist on the server side but why it still works normally. Of course, you can copy the server-side socket.io.js file to locally and make it a client-side js file, so you don’t have to request this js file from the Node server every time, which enhances stability. The second point is to use var socket = io.connect('website address or ip'); to obtain the socket object, and then you can use socket to send and receive events. Regarding event processing, the above code means that after receiving the "news" event, the received data is printed and the "other event" event is sent to the server.
Note: The built-in default event name, such as "disconnect" means the client connection is disconnected, "message" means the message is received, etc. For custom event names, try not to double the name with the default event names built in Socket.IO, so as not to cause unnecessary trouble.
4. Other common APIs
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.
5. Build a chat room using Socket.IO
Finally, we end this article with a simple example. Using Socket.IO to build a chat room is about 50 lines of code, and the real-time chat effect is also very good. The following key codes are posted:
Server (socketChat.js)
The code copy is as follows:
// A dictionary for client connection, when a client connects to the server,
// A unique socketId will be generated, and the dictionary will hold the mapping of socketId to user information (nickname, etc.)
var connectionList = {};
exports.startChat = function (io) {
io.sockets.on('connection', function (socket) {
//Save socketId and username when client connection
var socketId = socket.id;
connectionList[socketId] = {
socket: socket
};
//The user enters the chat room event and broadcasts his username to other online users
socket.on('join', function (data) {
socket.broadcast.emit('broadcast_join', data);
connectionList[socketId].username = data.username;
});
//The user leaves the chat room incident and broadcasts his departure to other online users
socket.on('disconnect', function () {
if (connectionList[socketId].username) {
socket.broadcast.emit('broadcast_quit', {
username: connectionList[socketId].username
});
}
delete connectionList[socketId];
});
//User speech incident, broadcast the content of their speech to other online users
socket.on('say', function (data) {
socket.broadcast.emit('broadcast_say',{
username: connectionList[socketId].username,
text: data.text
});
});
})
};
Client(socketChatClient.js)
The code copy is as follows:
var socket = io.connect('http://localhost');
//After connecting to the server, submit a "join" event immediately and tell others your username
socket.emit('join', {
username: 'Username hehe'
});
//After receiving the broadcast of joining the chat room, the message will be displayed
socket.on('broadcast_join', function (data) {
console.log(data.username + 'Added to chat room');
});
//After receiving the broadcast leaving the chat room, the message is displayed
socket.on('broadcast_quit', function(data) {
console.log(data.username + 'Leave the chat room');
});
//After receiving a message sent by someone else, the message will be displayed
socket.on('broadcast_say', function(data) {
console.log(data.username + 'say: ' + data.text);
});
//Here we assume that there is a text box textarea and a send button.btn-send
//Bind event using jQuery
$('.btn-send').click(function(e) {
//Get text of the text box
var text = $('textarea').val();
//Submit a say event and the server will broadcast it when it receives it.
socket.emit('say', {
username: 'Username hehe'
text: text
});
});
This is a simple chat room DEMO that you can expand as you want. Socket.IO is basically the submission and reception processing of various events, and the idea is very simple.