我已经为使用TCP通讯的应用程序导入了网络套接字的所有必需导入。我想从两侧删除聊天,例如在whatsapp中,阅读消息等,即任何应用程序的聊天模块中的所有基本功能,所有所需的存储库都已注入,代码中未提及。 代码正在使用npm run start:dev运行,没有任何错误。
我通过邮递员用Chat控制器测试了上面的代码,它成功地将所需的数据保存在数据库中,但是当在应用程序中使用实时时,则不会触发事件。
我想做的是:
说明::我想为类似于whats-app聊天的应用程序实现有效的聊天模块api。 为此,我想请求要保存在数据库中的用户信息 现在,我已经在聊天服务文件中为相同的函数创建了函数,还在聊天网关文件中创建了事件,但是**问题是当从以下位置触发事件时,我无法与前端连接**前端的行为不符合预期,即事件根本不指向我的函数,导致数据库中没有数据输入。
编辑:1 我已经进行了一些更改,现在可以正常使用了。稍后,我将发布更改。
这是我的代码:
import { SubscribeMessage, WebSocketGateway,OnGatewayInit, WsResponse, OnGatewayConnection, OnGatewayDisconnect, WebSocketServer} from '@nestjs/websockets';
import { Logger, Req } from '@nestjs/common';
import { Socket, Server } from 'socket.io';
import { ChatService } from './chat.service';
import {CreateChatDto} from './dto';
import { Chats } from './entities/chat.entity';
import { ChatTos } from './entities/chat-to.entity';
import { Users } from '../user/entities/user.entity';
import { Repository, getRepository,Between, DeleteResult, UpdateResult, getConnection } from 'typeorm';
import { Events } from '../event/entities/event.entity';
import { Teams } from '../team/entities/team.entity';
import { UserService } from '../user/user.service';```
**Below code is for websocket chat.**
```@WebSocketServer() wss: Server;
private logger: Logger = new Logger('ChatGateway');
wsClients=[];
afterInit(server: Server) {
console.log('Initialized!')
this.logger.log('Initialized!');
}
handleDisconnect(client: Socket) {
console.log("disconnected")
this.logger.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: any) {
this.wsClients.push(client);
}
@SubscribeMessage('msgToServer')
async handleMessage(@Req() request, client:Socket,dto: CreateChatDto) {
// const {id,message,to_id,message_type,event_id,team_id } = dto;**commented code**
const jwtData = await this.userService.jwtData(request.headers.authorization);
const logged_id = jwtData.id;
this.chatService.sendMessage(logged_id, dto);
console.log("savedChat")
client.send('msgToServer', dto);
return ({message:"Message sent"});
}
@SubscribeMessage('readMessage')
async readMessage(@Req() request, client:Socket,dto: CreateChatDto) {
// const {id,message,to_id,message_type,event_id,team_id } = dto;
const jwtData = await this.userService.jwtData(request.headers.authorization);
const logged_id = jwtData.id;
this.chatService.readMessage(logged_id, dto);
console.log("readChat")
client.emit('readMessage', dto);
return ({message:"Message read"});
}
@SubscribeMessage('deleteMessage')
async deleteMessage(@Req() request, client:Socket,dto: CreateChatDto) {
// const {id,message,to_id,message_type,event_id,team_id } = dto;
const jwtData = await this.userService.jwtData(request.headers.authorization);
const logged_id = jwtData.id;
this.chatService.deleteMessage(logged_id, dto);
console.log(" delete Chat")
client.emit('deleteMessage', dto);
return ({message:"Message deleted"});
}
}```