HenningM / express-ws

WebSocket endpoints for express applications
BSD 2-Clause "Simplified" License
877 stars 142 forks source link

Does express-ws support http2? #165

Open you-hengh opened 6 months ago

you-hengh commented 6 months ago

As mentioned in the title, does express-ws support HTTP2? I have successfully docked data using the WSS protocol, but I still want to be able to use HTTP2.

This is my app.js:

import express from 'express'
import expressWs from 'express-ws'
import path from 'node:path'
import https from 'node:https'
// import http2 from 'node:http2'
import fs from 'fs-extra'

import router from './routers/index.js'

const app = express()

// Read SSL certificates and private keys
const options = {
  key: fs.readFileSync('/***/***.key'),
  cert: fs.readFileSync('/***/***.pem'),
}
const httpsServer = https.createServer(options)
// const httpsServer = http2.createSecureServer(options)  // Building a link using HTTP2 failed for unknown reasons

//Mixing the WebSocket service into the app is equivalent to adding a .ws method to the app
expressWs(app, httpsServer)

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static(path.join(import.meta.dirname, 'public')))

// Using the Routing Module
app.use('/api', router)

// app.listen(3000, () => {
//   console.log('Service started: http://localhost:3000')
// })

// Start the HTTP/2 server and listen on the port
httpsServer.on('request', app)
httpsServer.listen(3000, () => {
  console.log('Service started: https://localhost:3000')
})

This is my router file:

import express from 'express'
import { nanoid } from 'nanoid'
import expressWs from 'express-ws'   // Express-ws must be introduced again, otherwise an error will be reported. The router has no ws method.
import { getMenu, getName } from '../utils/index.js'

const router = express.Router()
expressWs(router) //I don't quite understand why this step is repeated, but with it the program works fine

// Create ws link, share menu status
router.ws('/:tableID', (ws, req) => {
  // After the first link, provide the menu content and username
  ws.on('message', msg => {
    const message = JSON.parse(msg)
    if (message.type === 'getName') {
      ws.send(
        JSON.stringify({
          menu: getMenu(),
          tableID: req.params.tableID,
          username: getName(),
          orderID: nanoid(),
        })
      )
    } else {
      ws.send('Send message format error')
    }
  })
})

export default router

The above is the basic content of my websocket. If you need more detailed instructions, you can leave a message here. I expect to be able to use HTTP2. Its function further reduces network overhead and is a very good protocol