Home  >  Article  >  Web Front-end  >  How socket.io’s instant messaging front-end cooperates with Node

How socket.io’s instant messaging front-end cooperates with Node

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-04-23 09:16:491802browse

This article will give you a detailed introduction to the socket.io instant messaging front-end method of cooperating with Node. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How socket.io’s instant messaging front-end cooperates with Node

First look at the effect, hahaha it’s still so small
How socket.io’s instant messaging front-end cooperates with Node

First we need to
create a new folder
and Quickly generate a package.json file

npm init -y  //生成一个package.json
npm i express
npm i socket.io

Create a new serverRoom.js file

const express = require('express')const app = express()let port =3000app.get('/',(req,res,next)=>{
    res.writeHead(200, { 'Content-type': 'text/html;charset=utf-8' })
    res.end('欢迎来到express')
    next()})const server = app.listen(port,()=>{console.log('成功启动express服务,端口号是'+port)})

Cmd at the location of the current file

node serverRoom.js  
//或者使用  快速更新serverRoom.js的变化 同步到当前打开的服务器
//可以通过 npm i nodemon -g 下载到全局 使用很是方便 不亦乐乎
nodemon serverRoom.js

Start successfully

How socket.io’s instant messaging front-end cooperates with Node
There is no problem if you look at

How socket.io’s instant messaging front-end cooperates with Node
in the browser. Next we continue to write serverRoom.js

const express = require('express')const app = express()let port =3000app.get('/',(req,res,next)=>{
    res.writeHead(200, { 'Content-type': 'text/html;charset=utf-8' })
    res.end('欢迎来到express')
    next()})const server = app.listen(port,()=>{console.log('成功启动express服务,端口号是'+port)})//引入socket.io传入服务器对象 让socket.io注入到web网页服务const io = require('socket.io')(server);io.on('connect',(websocketObj)=>{  //connect 固定的  
    //链接成功后立即触发webEvent事件
    websocketObj.emit('webEvent','恭喜链接websocket服务成功:目前链接的地址为:http://127.0.0.1:3000')})

Front-end html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- 通过script的方式引入 soctke.io -->
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <!-- 为了操作dom方便我也引入了jq -->
    <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
    <title>myWebsocket</title></head><body>
    <p class="myBox">
        <input class="inp" type="text"> <button onclick="sendFun()">点我</button>
    </p>
    <script>
        //页面打开自动链接 http://localhost:3000 后端服务
        let mySocket = io("http://localhost:3000") //直接写后端服务地址
        //一直在监听webEvent 这个事件
        mySocket.on(&#39;webEvent&#39;, (res) => {
            window.alert(res)
        })
        //获取input的输入内容//将来传给服务器
        function sendFun() {
            console.log($(&#39;.myBox>.inp&#39;).val())
        }
    </script></body></html>

When the service is started, the front-end page will automatically link to our back-end service, and the link will successfully trigger the webEvent event (the name can be defined by yourself) , the front and back must be unified), the front end listens to the webEvent event to obtain the content sent by the server and displays it through alert.

Okay, the above is no problem and the following is easy to understand:

The function to be implemented below is to enter something in the input input box and pass it to the server. The server returns an array and the front end displays it in Page

//Of course it’s just for learning the functions, don’t care about the examples

Look at the front-end Html

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <!-- 通过script的方式引入 soctke.io -->
    <script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
    <!-- 为了操作dom方便我也引入了jq -->
    <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
    <title>myWebsocket</title></head><body>
    <p class="myBox">
        <input class="inp" type="text"> <button onclick="sendFun()">点我</button>
        <p class="myBoxChild"></p>
    </p>
    <script>
        //页面打开自动链接 http://localhost:3000 后端服务
        let mySocket = io("http://localhost:3000") //直接写后端服务地址
        //一直在监听webEvent 这个事件
        mySocket.on(&#39;webEvent&#39;, (res) => {
            window.alert(res)
        })
        mySocket.on(&#39;sendFunEventCallBack&#39;, (res) => {
            console.log(res, &#39;sendFunEventCallBackRes&#39;)
            let data = JSON.parse(res)
            let str = &#39;&#39;
            for (let i = 0; i < data.length; i++) {
                str += `<p>${data[i]}</p>`
            }
            $(&#39;.myBoxChild&#39;)[0].innerHTML = str        })

        //获取input的输入内容//将来传给服务器
        function sendFun() {
            if ($(&#39;.myBox>.inp&#39;).val() != &#39;&#39;) {
                mySocket.emit(&#39;sendFunEvent&#39;, $(&#39;.myBox>.inp&#39;).val())
                $(&#39;.myBox>.inp&#39;)[0].value = &#39;&#39;
            } else {
                alert(&#39;输入字符&#39;)
                return
            }
        }
    </script></body></html>

Server

const express = require(&#39;express&#39;)const app = express()let port =3000app.get(&#39;/&#39;,(req,res,next)=>{
    res.writeHead(200, { &#39;Content-type&#39;: &#39;text/html;charset=utf-8&#39; })
    res.end(&#39;欢迎来到express&#39;)
    next()})const server = app.listen(port,()=>{console.log(&#39;成功启动express服务,端口号是&#39;+port)})//引入socket.io传入服务器对象 让socket.io注入到web网页服务const io = require('socket.io')(server);let arr=['恭喜链接websocket服务成功:目前链接的地址为:http://127.0.0.1:3000']io.on('connect',(websocketObj)=>{  //connect 固定的  
    //链接成功后立即触发webEvent事件
    websocketObj.emit('webEvent',JSON.stringify(arr));
    //监听前端触发的 sendFunEvent  事件 
    websocketObj.on('sendFunEvent',(webres)=>{
        arr.push(webres)
        //触发所以的 sendFunEventCallBack 事件  让前端监听
        io.sockets.emit("sendFunEventCallBack", JSON.stringify(arr));
    })})

After opening the page, Enter a value in the input, click the button to trigger the sendFun function, trigger the custom event sendFunEvent and transmit the input value to the server. The server listens to the sendFunEvent event, pushes the data into the array, and triggers the sendFunEventCallBack event, passing the array as a JSON string. To the front end, the front end listens to the sendFunEventCallBack event, obtains the array, JSON serializes, and loops the data to the page. This is the entire process.

Open multiple front-end pages for real-time updates and chat.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How socket.io’s instant messaging front-end cooperates with Node. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete