文档地址:socket.io
安装socket.io
npm i socket.io -S
参考代码
import express from 'express';
import { Server } from 'socket.io';
import http from 'http';
const app = express();
const server = http.createServer(app);
const io = new Server(server);
io.on("connection", (socket) => { // 连接成功时调用
socket.on('sendMsg', (data) => { // 监听客户端的sendMsg事件
io.emit('receiveMsg', data); // 派发事件
});
});
server.listen(8090, () => { // 监听端口
console.log('http://localhost:8090');
});
安装socket.io-client
yarn add socket.io-client
配置代理,解决跨域(vite.config.ts)
export default defineConfig({
...
server: {
proxy: {
'/socket.io': {
target: 'ws://localhost:8090', // 必须与服务端监听的端口对应
ws: true
}
}
}
...
});
参考代码
<template>
<div class="app">
<div>
<div v-for="(item, index) in msgData" :key="index">{{item}}</div>
</div>
<div>
<input v-model="msg" placeholder="请输入消息" type="text" />
<button @click="sendMsg">发送消息</button>
</div>
</div>
</template>
<script lang="ts" setup>
import { io } from 'socket.io-client';
import { ref } from 'vue';
const msgData = ref<string[]>([]);
const msg = ref('');
const socket = io({
reconnection: true,
forceNew: true,
transports: ['websocket'],
path: '/socket.io/' // 必须与代理设置的key一样
});
socket.on('receiveMsg', (arg: string) => { // 监听事件消息
msgData.value.push(arg);
});
const sendMsg = () => {
if(!msg.value){
return;
}
socket.emit('sendMsg', msg.value); // 发送消息
}
</script>
上面是简单的聊天使用,后续有时间会更新更多API,及群聊等功能的使用