koa中http服务与websocket服务共享端口

2020-09-10 16:06:15 浏览数 (1)

记录下如何在koa中共享http与websocket服务端口

1.安装ws模块

代码语言:javascript复制
npm install ws

2.服务端

代码语言:javascript复制
const Koa = require('koa')
const app = new Koa()
const path = require('path')
const ws = require('ws')

app.use(require('koa-static')(path.join(__dirname)   '/public'))

let server = app.listen(4000, () => {
  let port = server.address().port
  console.log('应用实例,访问地址为 http://localhost:'   port)
})

const wss = new ws.Server({ server })
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message)
  })
})

3.客户端

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ws测试</title>
  </head>
  <body>
    <script>
      var ws = new WebSocket('ws://localhost:4000/')
      ws.onopen = function () {
        console.log('connected')
        setTimeout(function () {
          ws.send('hello')
        }, 2000)
      }
      ws.onmessage = function (e) {
        console.log(e.data)
      }
    </script>
  </body>
</html>

4.运行效果

0 人点赞