const express = require('express') const mysql = require('mysql2') const jwt = require('jsonwebtoken') const WebSocket = require('ws');
const app = express();
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') console.log(payload.data); if(payload){ res.send({ username: payload.data, status: 1 }) }else{ res.status(500) } })
app.listen(3000,()=>{ console.log('服务器已启动,3000端口正在监听....'); })
function getConfig(){ return { host:'127.0.0.1', port: 3306, user: 'root', password: 'Zpl13189417387', database:'jwt', connectionLimit:1 } }
const WebSocketServer = WebSocket.WebSocketServer
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws,req) { const myURL = new URL(req.url , 'http://127.0.0.1:8080') console.log(myURL.searchParams.get('token')); try { const payload = jwt.verify(myURL.searchParams.get('token'),'lam') if(payload){ ws.send(createMessage( WebSocketType.GroupChat, '广播', '欢迎来到聊天室!' )) ws.user = payload sendAll() } } catch(err) { console.log(`错误信息${err}`); } ws.on('message', function message(data) { const msgObj = JSON.parse(data) switch (msgObj.type) { case 1: ws.send(createMessage( 1,null, JSON.stringify(Array.from(wss.clients).map(item=>item.user)) )) break; case 2: wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) {
client.send(createMessage( 2, ws.user.data, msgObj.data ), { binary: false }); } }); break; case 3: wss.clients.forEach(function each(client) { if (client.user.data === msgObj.to && client.readyState === WebSocket.OPEN) {
client.send(createMessage( 3, ws.user.data, msgObj.data ), { binary: false }); } }); break; } });
ws.on('close', ()=>{ wss.clients.delete(ws.user) sendAll() }) });
const WebSocketType = { Error:0, GroupList:1, GroupChat:2, SingleChat:3 }
function createMessage(type,user,data){ return JSON.stringify({ type, user, data }) }
function sendAll(){ wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(createMessage( 1,null, JSON.stringify(Array.from(wss.clients).map(item=>item.user)) )) } }); }
|