1、初始化(確保當(dāng)前電腦有node環(huán)境)
npm init
2、安裝express
npm i express
npm i ws
文件結(jié)構(gòu)
3、編寫相關(guān)代碼啟動node服務(wù)(server.js)
//導(dǎo)入下列模塊,express搭建服務(wù)器,fs用來操作文件、ws用來實現(xiàn)webscoket
const express = require("express")
const path = require("path")
const app = express()
const fs = require("fs")
const txt = fs.readFileSync('./msg.text','utf-8')
console.log("文件運行成功",txt)
app.all('*', function (req, res, next) {
// 解決跨域
res.header('Access-Control-Allow-Origin', '*');
// 設(shè)置相應(yīng)頭數(shù)據(jù)
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
// 設(shè)置接收的方法
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
next();
});
//編寫127.0.0.1:3333/index接口
//返回值為resObj
app.get("/index", (req, res) => {
console.log("請求攜帶的參數(shù)", req)
const resObj = {
code: "200",
msg: '成功了',
data: [1, 2, 3]
}
//obj填寫到msg.text文件中
fs.writeFileSync('./msg.text',JSON.stringify(resObj ),'utf-8')
res.json(resObj )
})
const serve = app.listen(3333, () => {
console.log('服務(wù)啟動成功');
})
//導(dǎo)入ws模塊,實現(xiàn)雙向通訊
const WebSocket = require('ws');
const clients = new Set();
// 創(chuàng)建 WebSocket 服務(wù)器
const wss = new WebSocket.Server({server:serve });
// 監(jiān)聽連接事件
wss.on('connection', (ws) => {
clients.add(ws);
// 監(jiān)聽消息事件
//以廣播的形式發(fā)送消息
ws.on('message', (message) => {
clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
// 發(fā)送消息到客戶端
client.send(message);
}
});
});
// 監(jiān)聽關(guān)閉事件
ws.on('close', () => {
console.log('Client disconnected');
});
});
4、啟動服務(wù)
node server.js
5、編寫前端(客戶端)代碼
ws.js文章來源:http://www.zghlxwxcb.cn/news/detail-561045.html
const url = "ws://127.0.0.1:3333"
const ws = new WebSocket(url)
ws.onmessage = (e) => {
console.log('接受到信息___________________>>>>>>>>>', e);
}
ws.onerror = function (err) {
console.log(err)
}
ws.onclose = function (e) {
console.log("中斷連接", e)
}
ws.onopen = function (e) {
console.log("打開連接", e)
}
export default ws
App.vue文章來源地址http://www.zghlxwxcb.cn/news/detail-561045.html
<template>
<div>
<span @click="msgFn">點擊發(fā)送消息</span>
</div>
</template>
<script setup>
import ws from './ws.js'
const msgFn=()=>{
ws.send({name:"tjq說xxxx"})
}
</script>
<style scoped></style>
到了這里,關(guān)于鞏固一下NodeJs的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!