Egg 使用 Websocket
1. 安装依赖
bash
npm install egg-websocket-plugin --save
2. 配置插件
- 插件里面配置
在 config/plugin.js
中添加以下配置
js
/** @type Egg.EggPlugin */
module.exports = {
websocket: {
enable: true,
package: "egg-websocket-plugin",
},
};
- 默认文件中配置
在 config/config.default.js
中添加以下配置
如果不需要 redis 则无需开启
js
// websocket
config.websocket = {
// redis: {
// port: 6380, // Redis 端口
// host: "127.0.0.1", // Redis 主机地址
// password: "auth", // Redis 密码(如果有的话)
// db: 0, // 数据库索引
// },
}; // 根据实际情况添加更具体的配置选项
3.使用
1.路由
- 这里的路由和传统不太一样
js
/**
* @param {Egg.Application} app - egg application
*/
module.exports = (app) => {
const { router, controller } = app;
router.get("/", controller.home.home);
// 配置websocket,这里的路哟用的不是router
app.ws.route("/ws", controller.home.ws);
};
2.控制器
- 新建一个控制器
js
"use strict";
const { Controller } = require("egg");
class HomeController extends Controller {
async home() {
const { ctx, app } = this;
ctx.body = "home";
}
async index() {
const { ctx, app } = this;
// 向房间 foo 发送消息
app.ws.sendTo("foo", "hello from index");
ctx.body = "index";
}
async ws() {
const { ctx } = this;
if (!ctx.websocket) {
throw new Error("this function can only be use in websocket router");
}
console.log("client connected");
const obj = { name: "连接成功 哈哈哈" };
setInterval(() => {
ctx.websocket.send(JSON.stringify(obj));
}, 2000);
ctx.websocket
.on("message", (msg) => {
console.log("receive", msg);
})
.on("close", (code, reason) => {
console.log("websocket closed", code, reason);
});
}
}
module.exports = HomeController;
3. 前端页面使用
html
<template>
<div>232</div>
</template>
<script setup>
import { reactive, ref, onMounted, onBeforeMount, onUnmounted } from "vue";
onMounted(() => {
initWebsocket();
});
onUnmounted(() => {
WebSocketonclose();
});
const ws = ref({
socket: null,
});
const initWebsocket = () => {
const wsuri = "ws://127.0.0.1:7001/ws";
ws.socket = new WebSocket(wsuri);
ws.socket.onmessage = WebSocketonmessage;
ws.socket.onopen = WebSocketonopen;
ws.socket.onclose = WebSocketonclose;
ws.socket.onerror = WebSocketonerror;
};
const WebSocketonopen = () => {
const data = { test: "123" };
WebSocketsend(JSON.stringify(data));
};
const WebSocketonclose = (e) => {
ws.socket && ws.socket.close();
ws.socket = null;
};
const WebSocketonmessage = (e) => {
const data = JSON.parse(e.data);
console.log(data);
};
const WebSocketonerror = (e) => {
initWebsocket();
};
const WebSocketsend = (data) => {
ws.socket.send(data);
};
</script>