新建文件夹,安装依赖
mkdir ws
cd ws
npm i koa
npm i ws
服务器端代码
// index.js
const Koa = require('koa')
const WebSocket = require('ws')
const app = new Koa()
const ws = new WebSocket.Server({ port: 3001 })
ws.on('connection', ws => {
console.log('server connection')
ws.on('message', msg => {
console.log('server receive msg:', msg)
// ... 然后也可以在这里ws.send 发送消息
})
ws.send('Information from the server')
})
app.use(async ctx => {
ctx.body = 'Hello Koa'
})
app.listen(3000)
客户端
<template>
<div>
首页
<el-input v-model="input" /> <el-button type="primary" @click="send">发送</el-button>
</div>
</template>
<script setup>
import { ref } from "vue";
let input = ref('')
var ws
function send() {
ws.onopen(input.value)
}
function WebSocketTest() {
if ("WebSocket" in window) {
alert("您的浏览器支持 WebSocket!");
ws = new WebSocket("ws://127.0.0.1:3001/");
ws.onopen = function (data) {
ws.send(data);
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("数据已接收..." + evt.data);
};
ws.onclose = function () {
alert("连接已关闭...");
};
}
else {
alert("您的浏览器不支持 WebSocket!");
}
}
WebSocketTest()
</script>
总结
- 服务器端使用 ws.on('message', callback)接收消息
- 服务器端使用 ws.send发送消息
- 客户端端使用 ws.onmessage接收消息
- 客户端使用 ws.onopen发送消息