How socket.io's instant messaging front-end cooperates with Node
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.
First look at the effect, hahaha it’s still so small
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
There is no problem if you look at
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('webEvent', (res) => { window.alert(res) }) //获取input的输入内容//将来传给服务器 function sendFun() { console.log($('.myBox>.inp').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('webEvent', (res) => { window.alert(res) }) mySocket.on('sendFunEventCallBack', (res) => { console.log(res, 'sendFunEventCallBackRes') let data = JSON.parse(res) let str = '' for (let i = 0; i < data.length; i++) { str += `<p>${data[i]}</p>` } $('.myBoxChild')[0].innerHTML = str }) //获取input的输入内容//将来传给服务器 function sendFun() { if ($('.myBox>.inp').val() != '') { mySocket.emit('sendFunEvent', $('.myBox>.inp').val()) $('.myBox>.inp')[0].value = '' } else { alert('输入字符') return } } </script></body></html>
Server
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);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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools