Does this package work for node client? #3888
Answered
by
darrachequesne
dukeliberal
asked this question in
Q&A
-
I build one nest server using socket.io, and try to use socket.io-client for nodejs client, the socket connected, but server can't communicate with client. Can some guys support this for me? Enviroments
Serverimport {
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
WsResponse,
MessageBody,
ConnectedSocket,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
@WebSocketGateway(3026, { transports: ['websocket'], upgrade: false })
export class EventsGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
public connectedSockets: Socket[] = [];
async handleConnection(@ConnectedSocket() client: Socket) {
try {
const hasConnect =
this.connectedSockets.findIndex(p => p.id === client.id) > -1;
if (hasConnect) {
this.connectedSockets = this.connectedSockets.filter(
p => p.id !== client.id,
);
}
console.log(client.id);
this.connectedSockets.push(client);
this.broadcastMessage('testing', 'msg');
} catch (error) {
console.log('error');
}
}
handleDisconnect(@ConnectedSocket() client: any) {
this.connectedSockets = this.connectedSockets.filter(
p => p.id !== client.id,
);
}
@SubscribeMessage('events')
handleEvent(@MessageBody() data: string, @ConnectedSocket() client: Socket) {
console.log(data, 'subscribe');
client.emit('message', '======');
return 'server return';
}
broadcastMessage(event: string, payload: any) {
for (const client of this.connectedSockets) {
client.send(event, payload);
client.emit(event, payload);
client.broadcast.emit(event, payload);
}
this.server.emit(event, payload);
}
} Clientconst io = require('socket.io-client');
const socket = io('http://localhost:3026', { transports: ['websocket'] });
socket.on('testing', function () {
console.log('testing');
socket.emit('events', 'hello', (data) => {
console.log(data);
});
});
socket.on('testing', function () {
console.log('testing');
}); |
Beta Was this translation helpful? Give feedback.
Answered by
darrachequesne
Apr 21, 2021
Replies: 1 comment
-
I think that's because Reference: https://docs.nestjs.com/websockets/gateways#installation |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
darrachequesne
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that's because
@nestjs/websockets
does includesocket.io@2
, which is not compatible withsocket.io-client@4
: nestjs/nest#5676Reference: https://docs.nestjs.com/websockets/gateways#installation