main.js
async function bootstrap() {
const privateKey = fs.readFileSync('certs/localhost.key', 'utf8');
const certificate = fs.readFileSync('certs/localhost.cert', 'utf8');
const httpsOptions = {key: privateKey, cert: certificate};
const server = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(server));
const httpsServer = https.createServer(httpsOptions);
app.useWebSocketAdapter(new ExtendedSocketIoAdapter(httpsServer));
app.use(cookieParser());
app.enableCors({
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
await app.init();
httpsServer.listen(3006);
}
ExtendedSocketIoAdapter.ts
import * as https from 'https';
import { IoAdapter } from '@nestjs/platform-socket.io';
import * as io from 'socket.io';
export class ExtendedSocketIoAdapter extends IoAdapter {
protected ioServer: io.Server;
constructor(protected server: https.Server) {
super();
const options = {
cors: {
origin: true,
methods: ['GET', 'POST'],
credentials: true,
},
};
this.ioServer = new io.Server(server, options);
}
create(port: number) {
console.log(
'websocket gateway port argument is ignored by ExtendedSocketIoAdapter, use the same port of http instead',
);
return this.ioServer;
}
}
단점 ::@WebSocketGateway({ namespace: 'videoChats' }) 여기서 namespace 같은 옵션이 무시된다. 같은 포트에 엔드포인트들이 동시에 연결된다.
wss://127.0.0.1:3000 으로 모든 namespace가 연결된다.
참고 )
https://stackoverflow.com/questions/70362938/nestjs-websocket-gateway-with-ssl-is-not-working
https://github.com/nestjs/nest/issues/126
https://stackoverflow.com/questions/57724813/nestjs-sets-both-http-and-https-servers/59084627#59084627