Commit ab1f5e38 authored by huanglu's avatar huanglu

feat: 优化聊天室

parent b6e74853
import { Controller } from 'egg';
export default class HomeController extends Controller {
public async list() {
const { ctx } = this;
const data = await ctx.service.news.list();
await this.ctx.render('list.nj', data);
}
}
import { Controller } from 'egg';
export default class HomeController extends Controller {
public async createRoom() {
const { ctx } = this;
ctx.body = await ctx.service.socket.createRoom();
}
public async joinRoom() {
const { ctx } = this;
ctx.body = await ctx.service.socket.joinRoom();
}
public async queryList() {
const { ctx } = this;
ctx.body = await ctx.service.socket.queryRooms();
}
}
......@@ -3,7 +3,7 @@ export default {
const meta = Object.assign({}, {
timestamp: Date.now(),
}, metadata);
console.log((this as any).redis);
return {
meta,
data: {
......@@ -12,4 +12,42 @@ export default {
},
};
},
async cacheGroupId(redis: any, groupId: string, socketId: string, groupName: string) {
const data = await redis.get('gk_chat_room');
if (data) {
const list = JSON.parse(data) || [];
const targetGroup = list.find((itm: any) => itm.groupId === groupId);
if (targetGroup) {
const sockets = targetGroup.groups || [];
sockets.push(socketId);
await redis.set('gk_chat_room', JSON.stringify(list));
return;
}
}
const value = JSON.stringify([{
groupId, groupName,
groups: [
socketId,
],
}]);
await redis.set('gk_chat_room', value);
},
async queryGroup(redis: any, groupId: string) {
const data = await redis.get('gk_chat_room');
const list = JSON.parse(data || '[]') || [];
const group = list.find((itm: any) => itm.groupId === groupId) || {};
return group;
},
async removeIdFromGroup(redis: any, groupId:string, socketId: string) {
const data = await redis.get('gk_chat_room');
if (data) {
const list = JSON.parse(data) || [];
const targetGroup = list.find((itm: any) => itm.groupId === groupId);
if (targetGroup) {
const sockets = (targetGroup.groups || []).filter((itm: any) => itm !== socketId);
targetGroup.groups = sockets;
await redis.set('gk_chat_room', JSON.stringify(list));
}
}
},
};
......@@ -8,10 +8,16 @@ export default class NspController extends Controller {
const socket = ctx.socket;
const client = socket.id;
try {
const { target, payload } = message;
if (!target) return;
const msg = ctx.helper.parseMsg('exchange', payload, { client, target });
nsp.sockets[target].emit('msg', msg);
const { target, payload, groupId } = message;
const group = await ctx.helper.queryGroup(app.redis, groupId);
if (group) { // 聊天室
group.groups.forEach((sck: string) => {
nsp.sockets[sck] && nsp.sockets[sck].emit('msg', message);
});
} else { // 单聊
const msg = ctx.helper.parseMsg('exchange', payload, { client, target });
target && nsp.sockets[target].emit('msg', msg);
}
} catch (error) {
app.logger.error(error);
}
......@@ -30,4 +36,4 @@ export default class NspController extends Controller {
app.logger.error(error);
}
}
}
}
\ No newline at end of file
......@@ -2,11 +2,7 @@ import { Context } from 'egg';
export default () => {
return async (_ctx: Context, next: any) => {
const { app } = _ctx;
const nsp = app.io.of('/') as any;
nsp.emit('updateList', nsp.sockets);
await next();
console.log('disconnection!');
nsp.emit('updateList', nsp.sockets);
// 断开连接后,删除对应的 群聊信息
};
};
......@@ -2,8 +2,10 @@ import { Context } from 'egg';
export default () => {
return async (ctx: Context, next: any) => {
ctx.socket.emit('res', 'packet received!');
console.log('packet:', ctx.packet);
ctx.socket.emit('res', {
time: new Date().getTime(),
success: 'received',
});
await next();
};
};
......@@ -6,6 +6,10 @@ export default (app: Application) => {
const { controller, router } = app;
router.get('/', controller.home.index);
router.get('/socket/queryRooms', controller.socket.queryList);
router.post('/socket/createroom', controller.socket.createRoom);
router.post('/socket/joinroom', controller.socket.joinRoom);
accountRouter(app);
socketRouter(app);
};
import { Service } from 'egg';
/**
* Test Service
*/
export default class Socket extends Service {
public async createRoom() {
const { app, ctx } = this;
const { redis } = app;
const { request } = ctx;
const body = request.body;
const { groupId, groupName, socketId } = body;
const group = await ctx.helper.queryGroup(redis, groupId);
if (group) {
return {
data: {
groupId,
groupName,
},
code: 1,
msg: '房间已存在',
};
}
await ctx.helper.cacheGroupId(redis, groupId, socketId, groupName);
return {
data: {
groupId,
groupName,
},
code: 0,
msg: 'success',
};
}
public async joinRoom() {
const { app, ctx } = this;
const { redis } = app;
const { request } = ctx;
const body = request.body;
const { groupId, socketId, groupName } = body;
await ctx.helper.cacheGroupId(redis, groupId, socketId, groupName);
return {
data: {
groupId,
id: socketId,
},
code: 0,
msg: 'success',
};
}
public async queryRooms() {
const { app } = this;
const { redis, logger } = app;
const data = await redis.get('gk_chat_room');
logger.info('queryRooms: ', data);
const list = JSON.parse(data || '[]') || [];
return {
data: list.map((itm: any) => ({ groupId: itm.groupId, groupName: itm.groupName })),
code: 0,
msg: '',
};
}
}
......@@ -2,6 +2,6 @@ import { Application } from 'egg';
export default (app: Application) => {
const { io } = app;
io.of('/').route('msg', (io.controller as any).nsp.send);
io.of('/').route('chatList', (io.controller as any).nsp.chatList);
};
......@@ -4,12 +4,12 @@
import 'egg';
import ExportAccount from '../../../app/controller/account';
import ExportHome from '../../../app/controller/home';
import ExportNews from '../../../app/controller/news';
import ExportSocket from '../../../app/controller/socket';
declare module 'egg' {
interface IController {
account: ExportAccount;
home: ExportHome;
news: ExportNews;
socket: ExportSocket;
}
}
......@@ -8,10 +8,12 @@ type CanExportFunc = AnyFunc<Promise<any>> | AnyFunc<IterableIterator<any>>;
type AutoInstanceType<T, U = T extends CanExportFunc ? T : T extends AnyFunc ? ReturnType<T> : T> = U extends AnyClass ? InstanceType<U> : U;
import ExportAccount from '../../../app/service/account';
import ExportHome from '../../../app/service/home';
import ExportSocket from '../../../app/service/socket';
declare module 'egg' {
interface IService {
account: AutoInstanceType<typeof ExportAccount>;
home: AutoInstanceType<typeof ExportHome>;
socket: AutoInstanceType<typeof ExportSocket>;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment