const express = require('express')
const app = express();
const mysql = require('mysql2') const jwt = require('jsonwebtoken') const server = require('http').createServer(app); const io = require('socket.io')(server);
io.on('connection', (socket,req) => { console.log('连接成功!!',socket.handshake.query.token);
try { const payload = jwt.verify(socket.handshake.query.token,'lam') if(payload){ socket.user = payload.data socket.emit( WebSocketType.GroupChat, createMessage('',`欢迎 "${socket.user}" 来到聊天室!!`) ) sendAll(io) } } catch (err) { console.log(`错误信息${err}`); }
socket.on(WebSocketType.GroupList,()=>{ console.log(Array.from(io.sockets.sockets).map(item=>item[1].user)); })
socket.on(WebSocketType.GroupChat,(msg)=>{ io.sockets.emit(WebSocketType.GroupChat, createMessage( socket.user, msg.data )) })
socket.on(WebSocketType.SingleChat,(msg)=>{ Array.from(io.sockets.sockets).forEach(item=>{ if(item[1].user === msg.to){ item[1].emit( WebSocketType.SingleChat, createMessage( socket.user, msg.data ) ) } }) })
socket.on('disconnect',()=>{ sendAll(io) }) });
app.use(express.json())
app.use(express.urlencoded({extended:false}))
app.use(express.static('./public'))
const config = getConfig()
const promisePool = mysql.createPool(config).promise()
app.post('/login', async (req , res)=>{ var admin = await promisePool.query( 'select * from admin where username=? and password=?', [req.body.username,req.body.password]) if(!admin[0].length){ res.send({ status:0, msg:'该用户不存在,请重新输入账号密码' }) }else{ const token = jwt.sign( {data:admin[0][0].username}, 'lam', {expiresIn: '30h'} )
res.header('Authorization' , token)
res.send({ status:1, data: admin[0], }) } })
app.get('/userinfo' , (req,res)=>{ const token = req.headers.authorization const payload = jwt.verify(token,'lam') if(payload){ res.send({ username: payload.data, status: 1 }) }else{ res.status(500) } })
server.listen(3000,()=>{ console.log('服务器已启动,3000端口正在监听....'); })
function getConfig(){ return { host:'127.0.0.1', port: 3306, user: 'root', password: 'Zpl13189417387', database:'jwt', connectionLimit:1 } }
var WebSocketType = { Error:0, GroupList:1, GroupChat:2, SingleChat:3 }
function createMessage(user,data){ return { user, data } }
function sendAll(io){ io.sockets.emit( WebSocketType.GroupList, createMessage( '', Array.from(io.sockets.sockets).map(item=>item[1].user) )) }
|