Oct1a

koa与websockect共用一个端口

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

1.安装ws模块

npm install ws

2.服务端

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.客户端

<!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 国际许可协议 进行许可。