1 Star 8 Fork 3

一天前 / ChatServe

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
app.js 2.43 KB
一键复制 编辑 原始数据 按行查看 历史
一天前 提交于 2020-05-17 12:22 . 忽略文件
/**
* 作者: liushun
* 时间: 2020/5/17
* 功能: 程序启动
* **/
import express from 'express';
import chalk from 'chalk';
import config from './config';
import router from './routes';
import './mongodb/db.js';
import bodyParser from 'body-parser'
import socket from 'socket.io'
import mongoose from 'mongoose'
import Socket from './models/socket'
import Message from './models/message'
import loger from './util/log'
import moment from 'moment'
import './redis/redis'
moment.locale('zh-cn');
const app = express();
// 服务器提交的数据json化
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
//验证
router(app);
//声明静态资源地址
app.use(express.static('image'));
//声明静态资源地址
app.use(express.static('voice'));
//声明静态资源地址
app.use(express.static('public'));
app.set('showStackError', true)
mongoose.set('debug', true)
const server = app.listen(config.port, () => {
console.log(
chalk.green(`成功监听端口:${config.port}`)
)
});
const io = socket(server);
global.io = io;
io.on('connect', (socket)=>{
console.log("socket connect");
socket.on('login',async (user, fn)=>{
let userId = user.id
let socketId = socket.id
let socketModal = {
socketId,
userId
}
const socketRes = await Socket.findOne({userId});
try{
if(!socketRes){
let socket = new Socket(socketModal);
await socket.save();
}else{
await Socket.updateOne({userId},{socketId})
}
}catch(e){
fn('连接服务器失败')
}
fn('连接服务器成功')
})
socket.on('message', async (message, fn) => {
fn(message);
const {fromName, fromId, avatar, toName, toId, type, text, roomId, duration} = message;
const messageId = await Message.find({'roomId': roomId}).count()
console.log(messageId)
let mess = {
username: fromName,
userId: fromId,
avatar,
msg: text,
type: type,
roomId,
messageId,
duration
}
const messModal = await new Message(mess).save()
const selfSockets = await Socket.findOne({userId: fromId});
// console.log(selfSockets)
io.to(selfSockets.socketId).emit('message', messModal);
const friendSockets = await Socket.findOne({ userId: toId });
io.to(friendSockets.socketId).emit('message', messModal);
})
})
io.on('disconnect', (socket)=>{
console.log("socket disconnect");
})
NodeJS
1
https://gitee.com/icfyl/ChatServe.git
git@gitee.com:icfyl/ChatServe.git
icfyl
ChatServe
ChatServe
master

搜索帮助