[Socket] Use Socket.io | socket broadcast in express

Introduction to Socket

  • Back-end and front-end push and send messages in real time

  • Used as scene:

    1. When user A likes or comments on user B, user B receives notifications of likes and comments from user A
    2. User online and offline status
    3. Chat, group chat, etc.
    • Socket official - https://socket.io/zh-CN
    • npm - https://www.npmjs.com/package/socket.io

socket.io vs websocket

  • websocket is a standard for HTML
    • MDN Reference → https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
  • Socket is a third-party library, and the socket that websocket can do can also do it
  • Both socket and websocket are used for real-time response business of client and server
  • There is a compatibility problem with websocket, if the browser does not support websocke, all previous efforts will be wasted
  • Socket supports more browsers, especially some lower version browsers.

Summary : When the server and client respond to business in real time, it isrelatively reliable to choose socket.io


socket download

npm i socket.io

socket points

  1. Socket event reference
 https://socket.io/zh-CN/docs/v4/emitting-events/
  1. socket server reference
https://socket.io/zh-CN/docs/v4/server-installation/
  1. socket client reference
https://socket.io/zh-CN/docs/v4/client-installation/

Basic use (vue)

front end

src/views/HomeView.vue

<template>
	{
   
   { msg }}
</template>
<script  setup>
import {
      
       io } from "socket.io-client"
import {
      
       ref} from "vue" 
// 若前后端不存在跨域,io里的参数可以省略
// const socket = io()

// 前后端存在跨域,将后端地址写上
const socket = io(`http://127.0.0.1:3001`)

const msg = ref()
// 连接成功
socket.on("connect", () => {
      
      
  // 监听后端的news
  socket.on('news', msg => {
      
      
  	msg.value = msg 
    console.log(msg)
  })
})
// 失去连接
socket.on("disconnect", () => {
      
      
  console.log('-------------')
})
</script> 

rear end

import {
    
     createServer } from 'http'
import {
    
     Server } from "socket.io"
import express from 'express'
const app = express()

//  重点 ——> 创建服务
const httpServer = createServer(app)
const io = new Server(httpServer, {
    
    
    // 允许跨域
    cors: {
    
    
        origin: "*"
    }
})

// 连接
io.on("connection", (socket) => {
    
    
    // 向客户端发送news
    socket.emit('news', {
    
     news: '你好!' });
})

// 重点 ——> 不能使app.listen监听端口,而是使用创建的httpServer监听
httpServer.listen('127.0.0.1', 3001)

Note: This article is only for personal understanding and vernacular interpretation, please refer to the official website interpretation .

Guess you like

Origin blog.csdn.net/qq_43614372/article/details/131152106