2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Usus NPM:
Website:https://socket.io/zh-CN/docs/v4/
Clientem API:https://socket.io/zh-CN/docs/v4/client-api/#socket
Primum, install socket.io-clientem in Vue project:
npm install socket.io-client
In tuo Vue componente, Socket.io hoc modo uti potes:
import io from 'socket.io-client';
// import { io } from "socket.io-client";
export default {
data() {
return {
socket: null
};
},
created() {
this.init()
},
methods: {
init(){
// 1. 连接到服务器
// 来自不同域,请确保在服务器上启用 跨域资源共享 (CORS)。
this.socket = io("https://server-domain.com");
// 来自同域
// this.socket = io();
console.log(this.socket.id); // undefined
// 连接服务器
this.socket.on('connect', () => {
console.log('已连接到服务器',this.socket.id);// "G5p5..."
});
// 2. 监听来自服务器的消息, 服务的的事件名 'news'
this.socket.on('news', (data) => {
console.log(data);
});
// 5. 断开连接时自动重连
// this.socket.on("disconnect", () => {
// this.socket.connect();
// });
},
// 发送消息按钮
sendMessage(message) {
// 检查连接状态
if (this.socket.connected) {
// 如果已连接,则直接发送任务信号
let post_data = {name: 'test'}
// 3. 发送消息到服务器, 'message' 客户端事件名
this.socket.emit('message', post_data, (response) => {
console.log(response); // "got it"
});
} else {
// 如果断开连接,则尝试重新连接
this.socket.connect();
// 监听连接成功事件
this.socket.on('connect', function() {
// 连接成功后发送任务信号
let post_data = {name: 'test'}
// 3. 发送消息到服务器, 'message' 客户端事件名
this.socket.emit('message', post_data, (response) => {
console.log(response); // "got it"
});
});
}
}
},
beforeDestroy() {
// 4. 断开连接
if (this.socket) {
this.socket.disconnect();
}
}
};