欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > vue2 使用 Socket.io 实现 WebSocket

vue2 使用 Socket.io 实现 WebSocket

2024/10/23 23:24:09 来源:https://blog.csdn.net/weixin_38797742/article/details/140358073  浏览:    关键词:vue2 使用 Socket.io 实现 WebSocket

使用 NPM:

官网:https://socket.io/zh-CN/docs/v4/
客户端API:https://socket.io/zh-CN/docs/v4/client-api/#socket

1、安装 Socket.io 客户端

首先,在你的 Vue 项目中安装 socket.io-client:

npm install socket.io-client
2、在 Vue 组件中使用 Socket.io

在你的 Vue 组件中,可以像这样使用 Socket.io:

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();}}
};
  • created() 钩子用来连接到服务器并设置消息监听器。
  • sendMessage() 方法用来发送消息到服务器。
  • beforeDestroy() 钩子在组件销毁前断开连接。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com