记录下如何在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>
本文介绍了如何在Koa应用中同时提供HTTP和WebSocket服务。通过使用'ws'模块,创建WebSocket服务器并监听同一端口4000。当WebSocket连接建立时,客户端发送消息'hello',服务器端接收到消息并在控制台打印。这个示例展示了在Node.js服务器端结合HTTP静态文件服务与WebSocket实时通信的能力。

546

被折叠的 条评论
为什么被折叠?



