Home  >  Article  >  Web Front-end  >  Use Node.js to write a multi-person real-time online chat room

Use Node.js to write a multi-person real-time online chat room

一个新手
一个新手Original
2017-10-06 10:40:482052browse

How to run the code:
1. Download the code locally, enter the root directory, and install the third-party module first, command: npm install
2. Start the server, command: node server. js
3. Open the browser and enter the address: http://127.0.0.1:3000/
4. Start a text chat or enter a command to create a new chat room;

The chat room implements the following functions:
1. Send messages to all users in the same room;
2. Display the list of available rooms;
3. Enter commands to join existing ones room or create a new room;
4. Notification of a new user entering the room;
5. Enter a command to modify the user's nickname;

Although the implementation of the Node.js chat room code is simple, it shows how to build a real-time Important components and basic technologies required for web programs. Not only can you see how Node handles traditional HTTP data (such as static files) and real-time data (chat messages) at the same time, but you can also see how Node programs are organized, how dependencies are managed, and how one port handles HTTP and WebSocket at the same time.

Background knowledge
1. What is WebSocket?
WebSocket is a new network protocol based on TCP, which implements two-way communication between the browser and the server (allowing the server to actively send information to the client). Before the emergence of the WebSocket protocol, two-way communication was implemented through multiple HTTP link polling, resulting in a series of problems such as inefficiency. A simpler solution is to use a single TCP connection for bidirectional communication, which is what the WebSocket protocol provides.
2. What is Socket.IO?
In most cases, WebSocket is only supported by modern HTML5-compatible browsers, which means that some browsers may not support WebSocket. Socket.IO encapsulates WebSocket and other transmission methods. It provides an abstraction layer. If the browser does not implement WebSocket, Socket.IO will automatically enable an alternative, and the API provided to the outside world will still be the same.

The above is the detailed content of Use Node.js to write a multi-person real-time online chat room. For more information, please follow other related articles on the PHP Chinese website!

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