koa中http服务与websocket服务共享端口
【摘要】
记录下如何在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(req...
记录下如何在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>
文章来源: blog.csdn.net,作者:薛定喵君,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/jsxg2009/article/details/115244480
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)