websocket 如何在NestJs中创建基于https的套接字?

eulz3vhy  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(174)

我已经创建了一个套接字网关,它可以非常顺利地处理HTTP请求。现在,我尝试在NestJs中通过https请求连接套接字,但没有成功。我还尝试在@WebsocketGateway(5058, { origin : "*:*", secure: true })中给予额外的参数
我还检查了NestJs的官方文档,以在套接字上使用SSL,但没有发现任何东西。
下面是我的代码,我已经创建了每个文档。

import { InternalServerErrorException, BadRequestException } from '@nestjs/common';
import { SocketService } from './socket/socket.service';
import { Server, Socket } from 'socket.io';

@WebSocketGateway(5058, { origin : "*:*"} )
export class AppGateway implements OnGatewayConnection, OnGatewayInit {

    constructor(private socketService: SocketService) { }

    public userIds = [];

    afterInit(server: Server) {
        console.log("Socket server started");
        this.socketService.socket = server;
    }

    async handleConnection(client) {

        try {
            console.log(client.id);
            this.socketService.socket.to(client.id).emit('status', "connected = " + client.id);
        } catch (error) {
            throw new InternalServerErrorException(
                `Oops.something went wrong, please try again later`,
            );
        }
    }

    async handleDisconnect(client) {
        this.userIds = this.userIds.filter(user => user.conn_socket_id !== client.id);
    }
}

编辑:
我可以在使用HTTP请求时启动服务器并访问套接字,但我无法访问HTTPS请求的套接字。例如,http://example.com:5058对我有效,https://example.com:5058不起作用。

bz4sfanl

bz4sfanl1#

我已经通过在套接字端口上使用代理修复了它,所以如果我的套接字URL像**https://example.com:5058**,那么它应该从虚拟主机处理,并添加一个代理来让它工作。
不起作用的原因是,当您应用HTTPS时,它将在端口443上运行。但现在,当您在具有HTTPS的URL中应用其他端口时,它将不运行,并显示错误。
Apache反向代理参考:Link

相关问题