前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/socket.io/4.1.3/socket.io.min.js"></script>
<style></style>
</head>
<body>
<div id="box">
<div style="width:500px;height:100%;min-height:50px;border:1px blue solid">
<div v-for="item,index of list" :key="index">
<div style="color: red;">
<span>{{item.lufei}}</span>
<span>{{item.ll}}</span>
<span>{{item.shuo}}</span>
</div>
<div style="text-align: right;color: rgb(241, 12, 222);">
<span>{{item.shuo1}}</span>
<span>{{item.ss}}</span>
<span>{{item.suolong}}</span>
</div>
</div>
<input type="radio" v-model="sex" value="1" name="路飞">路飞
<input type="radio" v-model="sex" value="2" name="索隆">索隆
<!-- <div><span style="color: rgb(25, 152, 202);">{{shuru}}</span>-----正在输入</div> -->
</div>
<!-- <div>我输入的<span style="color: rgb(255, 21, 130);">{{ziji}}</span></div> -->
<div>
<span>内容:</span>
<input type="text" v-model="value1">
</div>
<button @click="btn">发送</button>
</div>
</body>
<script>
new Vue({
el:"#box",
data(){
return {
sex:0,
name1:'',
value1:'',
list:[
{lufei:'路飞',ll:':',shuo:'我是蒙奇D路飞',suolong:'索隆',ss:':',shuo1:'我是罗罗诺亚索隆'}
],
shuru:'',
ziji:'',
}
},
created(){
io.connect('http://localhost:8080').on('chat',data=>{
// console.log("接收",data);
if(this.sex==1){
this.list.push({
lufei:'路飞',
ll:':',
shuo:data.message
});
}else if(this.sex==2){
this.list.push({
suolong:'索隆',
ss:':',
shuo1:data.message
});
}
this.sex=0
this.value1=''
console.log(this.list);
})
io.connect('http://localhost:8080').on('userinput',data=>{
// console.log("谁在输入",data);
// 可用可不用
this.shuru=data
})
io.connect('http://localhost:8080').on('self',data=>{
// console.log("我输入了",data.message);
console.log(data.message);
})
},
methods:{
btn(){
io.connect('http://localhost:8080').emit('chat',{ username: this.name1,message: this.value1 })
},
inp(){
io.connect('http://localhost:8080').emit('userinput',this.name1)
},
}
})
</script>
</html>
node代码
下载的依赖
npm install express
npm install socket.io
const express = require('express');
const http = require('http');
const path = require('path')
const socket = require('socket.io');
var app = express();
// var server = app.listen(8080,()=>console.log("启动了8080端口"))
// 让服务器识别静态文件
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/',(req,res) => {
// 找到文件
res.sendFile(path.join(__dirname,'public/index.html'))
})
const io=socket(app.listen(8080))
// 测试连接是否成功
io.on('connection',(socket) => {
console.log("客户端链接了" ,socket.id);
socket.on('chat',data=>{
// 通知所有客户端
socket.broadcast.emit('chat',data)
console.log("chat",data);
// 触发 self 事件的客户端单独处理
socket.broadcast.emit('self',data)
})
// 监听谁在输入
socket.on('userinput',data=>{
// 发送
socket.broadcast.emit('userinput',data)
console.log("userinput",data);
})
})