const server = app.listen(3000)
require('./socket/socket')(server)
module.exports = app =>{
const io = require('socket.io')(app,{cors:true})
console.log('io服务开启')
const moment = require('moment')
let list = []
const message = []
io.on('connection',socket=>{
console.log('有人连接')
let user = ''
socket.on('login',obj=>{
list.push(obj)
user = obj
io.emit('person',list)
io.emit('enter',`欢迎${user.name}进入聊天室!`)
})
socket.on('message',obj=>{
message.push({user,message:obj})
const date = new Date()
const time = {
date:moment(date).format('YYYY年MM月DD日'),
time:moment(date).format('HH:mm:ss'),
init:date.getTime()
}
io.emit('message',{time,user,message:obj})
})
socket.on('disconnect',obj=>{
console.log('leave')
if(user) list = list.filter(r=>r.id!==user.id)
io.emit('person',list)
io.emit('enter',`${user.name}离开了聊天室!`)
})
})
}
npm i socket.io -s
npm i vue-socket.io -s
import SocketIO from "socket.io-client";
import vueSccketIO from "vue-socket.io";
Vue.use(
new vueSccketIO({
debug: true,
connection: SocketIO("ws://localhost:3000")
})
);
const io = require('socket.io')(app,{cors:true})
没错就是cors:true
import SocketIO from “socket.io-client”;
还记得上面这个引入吗
我们安装依赖的时候安装的是socket.io这个包
这个包中包含了socket.io-client但是与我们要用的不同
npm uninstall socket.io
npm i socket.io-client -s