在使用nestjs的websocket时,开启ssl,nestjs服务能使用https访问了,但是websocket却无法使用wss连接
nestjs
的github issues
中有相关问题,但是没有给出解决方案。经测试,发现WebSocketGateway
不配置端口,直接使用nestjs
服务的端口号连接即可
js
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as fs from 'fs'
const httpsOptions = {
key: fs.readFileSync('D:/wstStudy/webrtc/server.key'),
cert: fs.readFileSync('D:/wstStudy/webrtc/server.crt'),
};
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
httpsOptions
});
await app.listen(3000, '0.0.0.0');
}
bootstrap();
js
// socket.gateway.ts
import { WebSocketGateway, SubscribeMessage, MessageBody, OnGatewayConnection, OnGatewayInit, OnGatewayDisconnect, ConnectedSocket } from '@nestjs/websockets';
import { SocketService } from './socket.service';
// 这里不要配置端口号
@WebSocketGateway({ transports: ['websocket'], cors: '*'})
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
rooms: Set<string>
user: Map<string, string>
constructor(private readonly socketService: SocketService) {
this.rooms = new Set()
this.user = new Map()
}
afterInit(server: any) {
}
handleConnection(client: any, ...args: any[]) {
}
handleDisconnect(client: any) {
}
@SubscribeMessage('chat')
chat(@MessageBody() message: { room: string, msg: string }, @ConnectedSocket() client) {
client.to(message.room).emit('message', message.msg, this.user.get(client.id))
}
}
js
// 客户端
import { io } from 'socket.io-client'
const socket = io('https://192.168.3.22:3000', {
transports: ['websocket'],
query: {
}
})