一、后端
1.express 使用
先让文件夹初始化,创建 package.json 文件
npm init
安装express包
npm i express
2.express 初体验
//1、导入包
const express = require('express')
//2、创建应用对象
const app= express()
//3、创建路由规则
app.get('/home', (req, res) => {
res.end('Hello Express')
})
//4、监听端口 启动服务
app.listen(8000,()=>{
console.log('服务已启动,监听8000端口中');
})
看图:
3.安装 socket.io
npm install socket.io
//引入socket.io传入服务器对象 让socket.io注入到web网页服务
const io = require('socket.io')(server)
// 存入数据
let arr = ['恭喜链接websocket服务成功:目前链接的地址为:http://127.0.0.1:8000']
// 建立链接
io.on('connect',(e)=>{ //connect 固定的
// 链接成功马上响应webEvent
e.emit('webEvent',JSON.stringify(arr))
// 监听前端出发的sendEvent
e.on('sendEvent',(webres)=>{
console.log('接收前端发送的值',webres)
arr.push(webres)
// 触发所以的 sendEventCallBack 事件 arr中的数据
io.sockets.emit("sendEventCallBack",JSON.stringify(arr))
})
})
后端 index.js 代码
//1、导入包
const express = require('express')
//2、创建应用对象
const app= express()
//3、创建路由规则
app.get('/home', (req, res) => {
res.end('Hello Express')
})
//4、监听端口 启动服务
const server = app.listen(8000,()=>{
console.log('服务已启动,监听8000端口中');
})
//引入socket.io传入服务器对象 让socket.io注入到web网页服务
const io = require('socket.io')(server)
// 存入数据
let arr = ['恭喜链接websocket服务成功:目前链接的地址为:http://127.0.0.1:8000']
// 建立链接
io.on('connect',(e)=>{ //connect 固定的
// 链接成功马上响应webEvent
e.emit('webEvent',JSON.stringify(arr))
// 监听前端出发的sendEvent
e.on('sendEvent',(webres)=>{
console.log('接收前端发送的值',webres)
arr.push(webres)
// 触发所以的 sendEventCallBack 事件 arr中的数据
io.sockets.emit("sendEventCallBack",JSON.stringify(arr))
})
})
二、前端 vite 创建vue3
npm create vite@latest
npm install socket.io-client
import { io } from "socket.io-client";
<script setup lang="ts">
import { ref } from 'vue'
import {io} from 'socket.io-client' // 引入
const socket = io("127.0.0.1:8000",{
autoConnect:true, // 自动连接
});
const strres = ref()
// 有没有链接成功
socket.on('webEvent',(res)=>{
console.log(res)
})
// 接收信号
socket.on('sendEventCallBack',(res)=>{
console.log(res,'sendEventCallBack')
let data = JSON.parse(res)
let str:string = ''
for (let i = 0;i<data.length;i++){
str += `<p>${data[i]}</p>`
// strres.value = str;
}
strres.value = str;
})
const inp:any = ref()
const handleClick = () => {
if(inp.value != ''){
// 触发 后端的 sendEvent
socket.emit('sendEvent',inp.value )
}else {
console.log('输入为空')
}
}
</script>
<template>
<div class="myBox">
<div class="zzzz">
<input class="inp" v-model="inp" type="text">
<button @click="handleClick">提交</button>
</div>
<div class="myBoxChild">{{ strres }}</div>
</div>
</template>
<style scoped>
.zzzz {
position: fixed;
top: 20px;
left: 20px;
}
</style>