introduction
In modern network applications, real-time communication is becoming increasingly important. As a JavaScript running environment based on Chrome V8 engine, developers can run JavaScript code on the server side, providing a powerful real-time communication library. This article will use a simple example to show how to use and create a server that can enable real-time communication.
1. Environmental preparation
Before you start, make sure you have installed it. You also need to install the library, which can be installed through npm (package manager):
npm install
2. Create an HTTP server
First, we need to create an HTTP server that provides static file services, such as HTML pages. Here is the code to create an HTTP server:
const http = require("http"); const fs = require("fs"); // Create an HTTP serverlet server = ((request, response) => { // Read the file ("", (error, data) => { (200, { 'Content-Type': 'text/html' }); (data); }); }).listen(52273, () => { ('Server address: http://127.0.0.1:52273'); });
In this code, we use the http module to create a server that listens to port 52273. When an HTTP request arrives, the server will read and return the contents of the file.
3. Integration
Next, we will integrate to implement WebSocket communication. Here is the code to integrate and set up WebSocket event listening:
const socketio = require(""); // Create a WebSocket serverlet io = (server); // Listen to the connection event of the WebSocket server("connection", (socket) => { ("The client is already connected!!"); ('clientData', (data) => { ('Data sent by the client:', data); // Send serverData events and data to the client ('serverData', data); }); });
In this code, we first introducemodule and use
listen
The method creates a WebSocket server, bound to the HTTP server instance we created earlier. Then, we monitorconnection
Event, this event will be triggered when there is a new client connection.
Receive in the client:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- This line of code passes <script> Labels are introduced Client library。 This library allows browser and server creation WebSocket connect,and send or receive events。 Files are usually from the server side The library is provided under the specified path。 --> <script src="//"></script> <script> = function(){ // Connect to socket // This line of code creates a new socket object to establish a connection to the server. // The () method is a function provided by the library to initialize a new connection. // If the server address is not specified, it attempts to connect to the same host and port as the current page by default. // The specified address is such as: const socket = ('http://localhost:3000'); var socket = (); // Listen to events and data on the server ('serverData',(data)=>{ alert(data) // This is the data sent from the server }) // Create form click event ('button').onclick = ()=>{ // Get form data var text = ('text').value; // Send clientData events and data to the server ('clientData',text); } } </script> </head> <body> <input type="text" > <input type="button" value="send"> </body> </html>
4. Real-time communication
After the WebSocket connection is established, we can listen to the events sent by the client and send events to the client as needed. The following is the core code for real-time communication:
('clientData', (data) => { ('Data sent by the client:', data); // Send serverData events and data to the client ('serverData', data); });
This code is calledclientData
When the client sends this event, the server will receive the data and print it out. Then, the server usesemit
Method sends a name to the clientserverData
and send the received data back as a parameter.
5. Communication Type
Four communication types are mentioned in the comments:
One-way communication: Only the client sending the event can receive the message.
('connection', function (socket) { ('private message', function (msg) { ('serverData', data); }); });
Public Communications: All clients (including the client that sends the event) can receive messages.
('connection', function (socket) { ('private message', function (msg) { ('serverData', data); }); });
Broadcast communication: All other clients can receive messages except for the client that sends the event.
('connection', function (socket) { ('private message', function (msg) { ('serverData', data); }); });
Specify communication: It can be ensured that only the specified client receives the message, while other clients do not receive this message.
('connection', function (socket) { ('private message', function (msg) { ().emit('private message', msg); }); });
These communication types provide developers with flexible choices and can choose appropriate communication methods according to the needs of the application.
6. Overall code
Server (backend) code:
//Introduce moduleconst http = require("http") const fs = require("fs") const socketio = require("") // Create a serverlet server = ((request, response) => { // Read the file ("", (error, data) => { (200, { 'Content-Type': 'text/html' }) (data) }); }).listen(52273, () => { ('Server address: http://127.0.0.1:52273') }) // Create a WebSocket server// let io = (server);: Use the listen method of the module to create a WebSocket server,// and bind it to the HTTP server instance you created earlier.let io = (server); // Listen to the connection event of the WebSocket server, which is triggered when there is a new WebSocket client connection.var id=0 ("connection", (socket) => { // In the callback function, the socket parameter represents the WebSocket connection to the client. ("The client is already connected!!") id = ('The user has been online and has automatically assigned an id:',id) ('clientData', (data) => { // Output data sent by the client ('Data sent by the client:', data); // This code is sent to the server corresponding to the latest id; for example: there are three customer service terminals A, B, and C; if A sends a message, it will be sent to C (id).emit('serverData',data) // Send serverData events and data to the client // ('serverData', data); // 1. One-way communication type: When a client sends events and data, only he can receive messages // Code: ('serverData', data); // Communication type: When a client sends events and data, all other clients can receive messages, including the client sending the message itself // Code: ('serverData',data) // Communication type: When a client sends events and data, all other clients can receive messages, except for the client sending the message itself. // Code: ('serverData',data) // Communication type: A client sends events and data to a specified (id) client // Code: // id = // (id).emit('serverData',data) }) })
Client (front-end) code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- This line of code passes <script> Labels are introduced Client library。 This library allows browser and server creation WebSocket connect,and send or receive events。 Files are usually from the server side The library is provided under the specified path。 --> <script src="//"></script> <script> = function(){ // Connect to socket // This line of code creates a new socket object to establish a connection to the server. // The () method is a function provided by the library to initialize a new connection. // If the server address is not specified, it attempts to connect to the same host and port as the current page by default. var socket = (); // Listen to events and data on the server ('serverData',(data)=>{ alert(data) }) // Create form click event ('button').onclick = ()=>{ // Get form data var text = ('text').value; // Send clientData events and data to the server ('clientData',text); } } </script> </head> <body> <input type="text" > <input type="button" value="send"> </body> </html>
7. Conclusion
Through the above steps, we create a simple server that is able to handle HTTP requests and implement WebSocket communication using. This server can receive data sent by the client and send data to the client to realize real-time communication. This is just a basic example, and the powerful features are much more than that, they can support more complex real-time application scenarios such as multiplayer chat rooms, real-time games, etc.
The above is the detailed content based on and implementing real-time communication functions. For more information about real-time communication, please pay attention to my other related articles!