5分钟学会使用WebScoket

450 阅读1分钟

新建文件夹,安装依赖

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!");

    // 打开一个 web socket
    ws = new WebSocket("ws://127.0.0.1:3001/");
    ws.onopen = function (data) { // 发送消息的方法
      // Web Socket 已连接上,使用 send() 方法发送数据
      ws.send(data);
      // alert("数据发送中...");
    };

    ws.onmessage = function (evt) {
      var received_msg = evt.data;
      alert("数据已接收..." + evt.data); // 客户端在这里接收消息
    };

    ws.onclose = function () {
      // 关闭 websocket
      alert("连接已关闭...");
    };
  }

  else {
    // 浏览器不支持 WebSocket
    alert("您的浏览器不支持 WebSocket!");
  }
}
WebSocketTest()
</script>

总结

  • 服务器端使用 ws.on('message', callback)接收消息
  • 服务器端使用 ws.send发送消息
  • 客户端端使用 ws.onmessage接收消息
  • 客户端使用 ws.onopen发送消息