webSocket use-socket.io package use

Target

  • Use native JS to implement a WebSocket usage
  • Premise: A backend server (supporting socket) must be required

concept

It is a new technology, as long as the front-end and back-end support this protocol, == the back-end can actively push content to the front-end ==

Used in the project: make a smart customer service

Websocket performs a handshake through the 101 status code of the HTTP/1.1 protocol

In fact, a WebSocket channel is established between the VueCli scaffolding server and the browser

Once the newly implemented code is changed, the server actively pushes the updated js file to the browser, and the page is automatically updated

Protocol comparison

summary

  1. The webpack development server started by vuecli scaffolding also establishes a socket channel with the browser
  2. WebSocket is still based on TCP, but it will send a small packet to the background (heartbeat packet) every few seconds to maintain this connection

 The socket.io package uses:

The front end is very good at encapsulating WebSocket

The backend also encapsulates the socket code

Target

backend code

Install the relevant package configuration under the usage file of the server:

npm i socket.io
npm i express

 Create a server.js file in the root directory:

const express = require('express')
const app = express()
// const cors = require('cors')
// app.use(cors())
// eslint-disable-next-line node/no-path-concat
app.use(express.static(`${__dirname}/public`))// 设置服务器静态资源目录(目录下的资源可以让服务器直接访问)

const http = require('http').Server(app)// 使用http模块,实例化为http对象
http.listen(4005)// 设置服务器端口
const io = require('socket.io')(http)// socket.io要的http对象不是express对象,而是服务器上socket服务对象

// io.on('connection') -- 固定的, 用于 监测有没有人用socket服务链接我, 触发后面的函数
io.on('connection', function (socket) { // socket连接者对象
  // console.log('a user connected');
  socket.on('cTos', data => { // 谁来链接我, 我就给谁绑定一个事件叫cTos(随便), data接收的就是前端触发这个事件传递过来的聊天消息
    // io.sockets(拿到当前连接池里所有的socket对象-链接到我的所有人), emit()触发事件(前端事件叫sToC) ---- 广播
    io.sockets.emit('sToC', data) // 把当前收到的聊天消息, 发送给所有连接着(前端)
  })
})

Front-end code:

Create the index.js file under the public folder

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页</title>
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
    <!-- 1. 引入前端的socket.io注意版本 一定要跟后台对上 -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/client-dist/socket.io.min.js"></script>
    <div>
        <p>聊天窗口:</p>
        <hr>
        <div id="result"></div>
    </div>
    <div>
        <input type="text" placeholder="用户名" id="user">
        <input type="text" placeholder="消息" id="msg">
        <button id="btn">发送</button>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        // 2. 用io()函数链接socket服务器
        // 如果代码部署到了线上服务器, 这个localhost要换成线上的ip地址
        // 因为这个网页请求到本地浏览器上查看, 你要还是localhost那不是请求本地呢吗?
        const socket = io("ws://localhost:4005")
        $("#btn").on("click", function () {
            let user = $("#user").val()
            let msg = $("#msg").val()
            console.log(user, msg);

            // 3. socket触发后端的事件
            socket.emit('cTos', { user, msg })
        })

        socket.on('sToC', obj => {
            $("#result").append($(`<p>${obj.user} 说: ${obj.msg}</p>`))
        })

        axios({
        // url: '/api/nc/article/headline/T1348647853363/0-40.html'// 开发环境用
       url: 'http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html'// 上线环境
        }).then(res => {
        console.log(res)
       })
    </script>
</body>

</html>

third party use

Use plug-ins (SDK) packaged by third-party companies

Recommend 2 more commonly used instant messaging service platforms

  • ring letter
  • Rong Lianyun

The specific use process, according to the documentation, is integrated into your own project

summary

  1. You can use some packages instead of native WebSocket, for example, socket.io package
  2. The front end should pay attention to the js file using the client name
  3. You can also use third-party services to quickly integrate functions

Guess you like

Origin blog.csdn.net/m0_65812066/article/details/128642428