socketio / socket.io

Realtime application framework (Node.JS server)
https://socket.io
MIT License
60.93k stars 10.1k forks source link

WebSocket connection to xxx failed #4723

Closed Tyh2001 closed 1 year ago

Tyh2001 commented 1 year ago

Describe the bug

WebSocket connection to xxx failed

To Reproduce

Server socket.io server version: 4.6.1

Server Developing using Nestjs

// chat.gateway.ts

import {
  WebSocketGateway,
  SubscribeMessage,
  MessageBody,
  ConnectedSocket,
  OnGatewayConnection,
  WebSocketServer,
} from '@nestjs/websockets'
import { Socket, Server } from 'socket.io'

@WebSocketGateway(7171, { cors: true, transports: ['websocket'] })
export class ChatGateway implements OnGatewayConnection {
  @WebSocketServer()
  server: Server = new Server()

  handleConnection(client: Socket) {
    console.log('ok')

    client.join('room')
  }

  @SubscribeMessage('chat')
   handleMessage(
    @ConnectedSocket() client: Socket,
    @MessageBody() payload
  ) {
    this.server.to('room').emit('chat', payload)
  }
}
// main.js

import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { ExpressAdapter } from '@nestjs/platform-express'
import { IoAdapter } from '@nestjs/platform-socket.io'
import * as express from 'express'
import * as fs from 'fs'
import * as https from 'https'

const corsMiddleware = (req: any, res: any, next: () => void) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  )
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')

  next()
}

async function bootstrap() {
  const server = express()

  // https://docs.nestjs.cn/9/websockets?id=ws-%e5%ba%93
  const app = await NestFactory.create(AppModule, new ExpressAdapter(server))

  app.useWebSocketAdapter(new IoAdapter(app))
  app.enableCors() // 全局设置 WebSocket 跨域访问
  app.use(corsMiddleware)

  if (process.env.NODE_ENV === 'production') {
    const serverOptions = {
      key: fs.readFileSync('./key.pem'),
      cert: fs.readFileSync('./cert.pem'),
    }

    // 创建 HTTPS 服务器
    const httpsServer = https.createServer(serverOptions, server)

    await app.init()
    await httpsServer.listen(1216, () => {
      console.log('生产环境端口 1216 已经启动')
    })
  } else {
    await app.listen(1216, () => {
      console.log('开发环境 1216 端口已经启动')
    })
  }
}
bootstrap()

Socket.IO client version: 4.6.1

Server Developing using vue

import { io } from 'socket.io-client'

const socket = io('wss://xx.x.xx.xxx:7171', {
  transports: ['websocket'],
  withCredentials: true,
})

socket.on('connect', () => {
  console.log('ok')
})

socket.on('connect_error', (err) => {
  console.log('err', err)
})

Expected behavior

The code I am writing now runs normally in the development environment, but the connection failed in the production environment. I hope to connect successfully in the production environment as well

Platform:

Additional context

Currently, I can run normally in the local Windows development environment. However, when both the frontend and backend are deployed to the server, the WebSocket connection fails. I have placed the business code and WebSocket code in the same NestJS backend project because I want to access the data through port 1216, which is currently working fine. However, the WebSocket connection fails. I have configured the server's proxy settings, but it has not resolved the issue. If the information I provided is incomplete, feel free to ask me for more detailed configuration information.

34236ae897de91f9a4bedb706df777e
Wuchv commented 1 year ago

I had the same problem. Please tell me how to solve it. Thank you !

Tyh2001 commented 1 year ago

I had the same problem. Please tell me how to solve it. Thank you !

Are you in a development or production environment? If it is a development environment that requires the use of ws

Tyh2001 commented 1 year ago

I had the same problem. Please tell me how to solve it. Thank you !

Are you in a development or production environment? If it is a development environment that requires the use of ws

Wuchv commented 1 year ago

I had the same problem. Please tell me how to solve it. Thank you !

Are you in a development or production environment? If it is a development environment that requires the use of ws

It is ok in the development environment, but problem occurs when deploying to the production environment.