Home > Web Front-end > JS Tutorial > Socket.IO usage example in node.js_node.js

Socket.IO usage example in node.js_node.js

WBOY
Release: 2016-05-16 16:32:00
Original
1307 people have browsed it

1. Introduction

First is the official website of Socket.IO: http://socket.io

The official website is very simple, there is no API document, only a simple "How to use" for reference. Because Socket.IO is as simple, easy to use and easy to use as the official website.

So what exactly 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 select the best method according to the browser from various methods such as WebSocket, AJAX long polling, Iframe streaming, etc. to implement real-time network applications. It is very convenient and user-friendly, and the supported browsers are as low as IE5.5. It should be able to 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:

Copy code The code is as follows:

npm install socket.io

2.2 Combine express to build a server

express is a small Node.js web application framework that is often used when building HTTP servers, so I will explain it directly using Socket.IO and express as examples.

Copy code The code 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

It is mainly divided into two pieces of code, server-side and client-side, both of which are very simple.

Server (app.js):

Copy code The code is as follows:

//Continue 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 an event for the client to initiate a connection. When the connection is successful, the callback function with the socket parameter is called. When we use socket.IO, we basically handle user requests in this callback function.

The most critical functions of socket are the emit and on functions. The former submits (emits) an event (the event name is represented by a string). The event name can be customized. There are also some default event names, followed by an object. Represents the content sent to the socket; the latter receives an event (the event name is represented by a string), followed by a callback function called when the event is received, where data is the received data.

In the above example, we sent the news event and received the other event event, then the client should have corresponding receiving and sending events. Yes, client code is the exact opposite of server code and very similar.

Client (client.js)

Copy code The code is as follows:


<script><br> var socket = io.connect('http://localhost');<br> socket.on('news', function (data) {<br> console.log(data);<br> ​​​​ socket.emit('other event', { my: 'data' });<br> });<br> </script>

There are two points to note: the socket.io.js path must be written correctly. This js file is actually placed in the node_modules folder on the server side. When this file is requested, it will be redirected, so don’t be surprised that it does not exist on the server side. Why does this file still work normally? Of course, you can copy the server-side socket.io.js file locally and make it a client-side js file. This way, you don’t have to request the 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 the socket to send and receive events. Regarding event processing, the above code indicates that after receiving the "news" event, it prints the received data and sends the "other event" event to the server.

Note: The built-in default event names such as "disconnect" means that the client connection is disconnected, "message" means that a message is received, etc. The custom event name should not have the same name as the default event name built into Socket.IO to avoid unnecessary trouble.

4. Other commonly used 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 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.

5. Build a chat room using Socket.IO

Finally, we end this article with a simple example. Building a chat room with Socket.IO only requires about 50 lines of code, and the real-time chat effect is also very good. The key code is posted below:

Server (socketChat.js)

Copy code The code is as follows:

//A dictionary of client connections, when a client connects to the server,
//A unique socketId will be generated. The dictionary saves the mapping of socketId to user information (nickname, etc.)
var connectionList = {};

exports.startChat = function (io) {
​ io.sockets.on('connection', function (socket) {
//When the client connects, save the socketId and username
        var socketId = socket.id;
ConnectionList[socketId] = {
socket: socket
        };

//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;
        });

//User leaves the chat room event, broadcasting his/her 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 event, broadcast the content of his 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)

Copy code The code is as follows:

var socket = io.connect('http://localhost');
//After connecting to the server, immediately submit a "join" event and tell others your username
socket.emit('join', {
Username: 'Username hehe'
});

//After receiving the broadcast of joining the chat room, display the message
socket.on('broadcast_join', function (data) {
console.log(data.username 'Joined the chat room');
});

//After receiving the leave chat room broadcast, display the message
socket.on('broadcast_quit', function(data) {
console.log(data.username 'left the chat room');
});

//After receiving a message from someone else, display the message
socket.on('broadcast_say', function(data) {
console.log(data.username 'say: ' data.text);
});

//Here we assume there is a text box textarea and a send button.btn-send
//Use jQuery to bind events
$('.btn-send').click(function(e) {
//Get the 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, you can expand it according to your needs. Socket.IO is basically the submission and reception processing of various events. The idea is very simple.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template