//前端 main.js
import {useUserInfo} from "@/stores/user"
const store=useUserInfo()
let socket=io("http://localhost:3008",{
query:{
username:store.userInfo.uid
}
})
app.config.globalProperties.socket=socket
//服务端 ---app.js
const Koa = require("koa")
const app = new Koa()
const getSocket=require("./io/io.js")
const http = require('http').Server(app.callback())
const io = require("socket.io")(http, { cors: true })
io.listen(3008)
getSocket(io)
//io.js
module.exports =function(io){
const userList=[]
io.on("connection",(socket)=>{
const username=socket.handshake.query.username
if(!username)return
const userInfo=userList.find(user=>user.username===username)
if(userInfo){
userInfo.id=socket.id
}else{
userList.push({
id:socket.id,
username
})
}
// console.log(userList)
// io.emit('online',{userList})
socket.on('msg',(msgInfo)=>{
const user= userList.find(user=>user.username==msgInfo.touid)
if(user){
socket.to(user.id).emit('msg',msgInfo)
}
})
})
}
soket.io实现一对一通信
于 2023-09-18 23:35:25 首次发布