巩固一下NodeJs

1、初始化(确保当前电脑有node环境)

bash 复制代码
npm init 

2、安装express

bash 复制代码
npm i express
bash 复制代码
npm i ws

文件结构

3、编写相关代码启动node服务(server.js)

javascript 复制代码
//导入下列模块,express搭建服务器,fs用来操作文件、ws用来实现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', '*');
    // 设置相应头数据
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    // 设置接收的方法
    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("请求携带的参数", 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('服务启动成功');
})
//导入ws模块,实现双向通讯
const WebSocket = require('ws');
const clients = new Set();
// 创建 WebSocket 服务器
const wss = new WebSocket.Server({server:serve });
// 监听连接事件
wss.on('connection', (ws) => {
    clients.add(ws);
    // 监听消息事件
    //以广播的形式发送消息
    ws.on('message', (message) => {
        clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                // 发送消息到客户端
                client.send(message);
            }
        });
    });
    
    // 监听关闭事件
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

4、启动服务

bash 复制代码
node server.js

5、编写前端(客户端)代码

ws.js

javascript 复制代码
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

html 复制代码
<template>
	<div>
		<span @click="msgFn">点击发送消息</span>
	</div>
</template>
<script setup>
	import ws from './ws.js'
	const msgFn=()=>{
		ws.send({name:"tjq说xxxx"})
	}
</script>
<style scoped></style>
相关推荐
li35744 小时前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj4 小时前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel4 小时前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel4 小时前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
honder试试5 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky5 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
ponnylv5 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人5 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
西陵6 小时前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld6 小时前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试