search
HomeWeb Front-endJS TutorialSocket.IO usage example in node.js_node.js

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.

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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools