Using node and socket to realize online chat room

hang1017 2021-05-03 11:22:37
using node socket realize online

Use node and socket Realize online chat room

brief introduction

stay h5 End pass socket Realize the function of online chat room , Server based on node Realization .

The purpose of this tutorial is to simplify the explanation socketnode Implementation process . So I will skip h5 Static page development steps .

 Insert picture description here

One 、 Static page

 Insert picture description here

Here as far as possible with the simplest code to achieve the development of static pages , The whole page is divided into two parts :

1、 Chat window . Focus on the data structure of the object in the chat content object list

Parameters explain type
id - string | number
name user name string
type Message type , There can be words 、 picture 、 Expression, etc text | img etc.
message The message content -

2、 Bottom input box .

Branch : feat-h5-static-page Static page branching

Two 、 Establishing a connection


In the demo in , The main function of the server is to transfer messages . The message sent by Xiao Ming , adopt node socket Send it to everyone . Message structure and content can remain unchanged .

At present, the development of small partners with more are two libraries and ws.

  • The domain name of is http://
  • ws The domain name of is ws://

therefore Will be more in line with the needs of the actual project . Here and there To achieve this demo.

Project initialization

mkdir nodePkg
cd nodePkg
yarn init
yarn add express
yarn add node
yarn add
 Copy code 

Create a new folder to hold our node project , After project initialization , Add a few libraries to use .

newly build server.js File to achieve the function .

const express = require('express');
const http = require('http');
const socketIo = require('');
const app = express();
const server = http.Server(app);
const io = socketIo(server);
io.on('connection', function (socket) {
app.listen(8080, 'localhost', _ => {
console.log('demo The server has started , Access address http://localhost:8080')
 Copy code 
  • connection When a client initiates a connection , The server can pass through connection Establish a connection .
  • server.listen socket Connection port for :3000
  • app.listen(8080, '', () => {}) node service

Start the service

node server.js
 Copy code 

After writing the server , Now let's develop web Test whether the connection can be established successfully .


Pull the above h5 Branch code , Install the required libraries .

yarn add
 Copy code 

To write src/pages/index/index.tsx, The following code is abbreviated

import React, { FC, useEffect, useState } from 'react';
import io from '';
const HomePage: FC<HomePageProps> = ({ location }) => {
const [socket] = useState<any>(
io('http://localhost:3000', { transports: ['websocket'] }),
 Copy code 

When we start the project web After the project, you may find that the connection fails . Don't worry .node socket It takes time to start for the first time .

 Insert picture description here  Insert picture description here

When we see web The console at the end prints out connected: true, also node Server side on('connection') There are print messages on the terminal . It means that : The connection has been successfully established .

Branch : feat-connect Establish a connection branch

3、 ... and 、 send out 、 receive messages


There are omissions in the repeated code

io.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(' Server received : ', data);
socket.on('error', function (err) {
 Copy code 
  • socket.on('message' there message Want to be with web Keep the ends consistent , In this way, both sides can communicate with each other .
  • socket.send(data); The received message is retransmitted .


useEffect(() => {
socket.on('message', (msg: any) => {
setChatList([...chatList, msg]);
}, [socket]);
const sendMessage = () => {
socket.emit('message', {
id: random(),
type: 'text',
message: inputValue,
 Copy code 
  • socket.on web End receiving socket news .
  • socket.emit send out socket news , Note here :'message' Be consistent , In this way, both sides can communicate with each other .

Restart, start node service , Here's the effect .

 Insert picture description here

 Insert picture description here

Okay , So far we have successfully established the connection . But careful little friends will find that :

  • stay socket.on('message' The methods of , There's no way to get it in real time chatList The data of , The list cannot be appended .
  • At this moment if web If the client opens another page to send a message , The two pages don't communicate with each other .

Four 、 Multi person chat room


In the last legacy, there are two pages connected to the same socket The problem of not communicating with each other , Let's solve it together ~

Take a look at the present node The code at the end will find , Every socket Once the connection is established , It'll only be on the current socket Receiving and sending data , So different socket No intercommunication .

The solution is : We put all the socket Save the connection , One at a time socket As long as the connection receives information, it traverses each socket Send the message out .

let socketSet = new Set(); // Storage socket 
io.on('connection', function (socket) {
socket.on('message', function (data) {
socketSet.forEach(ws => {
if (ws.connected) { // Judge the current socket Is it connected 
} else {
socket.on('error', function (err) {
 Copy code 

Let's test the effect , You can see it in the picture below , Send a message in the chat box on the right , The chat box on the left can receive messages .

 Insert picture description here


web Let's optimize the next few small problems :

  • Leave the chat input box blank after sending the message
  • Use useRef Make sure the chat record can be updated in real time

Here's just the key code , You need to look at the full code feat-multi-chat Branch

import React, { FC, useEffect, useState, useRef } from 'react';
const chatListRef = useRef<any[]>([]);
useEffect(() => {
chatListRef.current = chatList;
}, [chatList]);
useEffect(() => {
socket.on('message', (msg: any) => {
setChatList([...chatListRef.current, msg]);
chatListRef.current = [...chatListRef.current, msg];
}, [socket]);
const sendMessage = () => {
 Copy code 

 Insert picture description here

5、 ... and 、 It's an extra function

Several small function points and optimization points are mentioned , It's achieved through text description .

1、loading state

chatList Add one to the object array of loading Of flag label .

Set to... When sending false, If through socket.on('message',{}) What is monitored is the current id When sending messages , The data again loading Set as true.

This idea can simulate , The status of sending the message and whether it was sent successfully .

2、 increase enter Monitoring events

// Keyboard binding events 
const handleEnterKey = (e: any) => {
if (e.keyCode === 13) {
// Call the method of sending information 
useEffect(() => {
document.addEventListener('keypress', (e) => handleEnterKey(e));
return () => document.removeEventListener('keypress', (e) => handleEnterKey(e));
}, []);
 Copy code 

project git Address

It's not easy to write , Give me one star Well ~


  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless