巩固一下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>
相关推荐
不想有bug的小菜鸟7 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_748238637 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u0100559608 分钟前
前端代理,解决跨域问题讲解
前端
quitv13 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238122 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星24 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
Joey_friends32 分钟前
【Linux】线程详解
开发语言
_GR38 分钟前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
一粒沙-43 分钟前
iOS 将GIF图分享至微信
前端·ios
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang