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

2020-09-09 21:20:26

记录下如何在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.运行效果

本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-ND 3.0 许可协议。可自由转载、引用,但需署名作者且注明文章出处。如转载至微信公众号,请在文末添加作者公众号二维码。

扫描下方二维码阅读当前文章

浏览器、微信扫码

评 论:

好文推荐
每天进步一点点~