vue使用websocket概念及示例
作者:小小程序员。
这篇文章主要为大家介绍了vue使用websocket概念及示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
概念部分:
1,WebSocket 是 HTML5 提供的 TCP 连接上进行全双工通讯的协议。一次握手之后,服务器和客户端可以互相主动通信,双向传输数据。
2,浏览器想服务器发送请求,建立连接之后,可通过send()方法想服务器发送数据,并通过message事件接受服务器返回的数据。
使用示例
<script>
export default {
mounted() {
this.connectWebsocket();
},
methods: {
connectWebsocket() {
let websocket;
if (typeof WebSocket === "undefined") {
console.log("您的浏览器不支持WebSocket");
return;
} else {
let protocol = "ws";
let url = "";
if (window.localtion.protocol == "https:") {
protocol = "wss";
}
// `${protocol}://window.location.host/echo`;
url = `${protocol}://localhost:9998/echo`;
// 打开一个websocket
websocket = new WebSocket(url);
// 建立连接
websocket.onopen = () => {
// 发送数据
websocket.send("发送数据");
console.log("websocket发送数据中");
};
// 客户端接收服务端返回的数据
websocket.onmessage = evt => {
console.log("websocket返回的数据:", evt);
};
// 发生错误时
websocket.onerror = evt => {
console.log("websocket错误:", evt);
};
// 关闭连接
websocket.onclose = evt => {
console.log("websocket关闭:", evt);
};
}
}
}
};
</script>
以上就是vue使用websocket概念及示例的详细内容,更多关于vue使用websocket的资料请关注脚本之家其它相关文章!
您可能感兴趣的文章:
- 一文详解websocket在vue2中的封装使用
- Vue项目中Websocket的使用实例
- 前端之vue3使用WebSocket的详细步骤
- vue3.0中使用websocket,封装到公共方法的实现
- vue3+ts+Vuex中使用websocket协议方式
- Vue项目使用Websocket大文件FileReader()切片上传实例
- vue项目使用websocket连接问题及解决
- Vue websocket封装实现方法详解
- vue基于websocket实现智能聊天及吸附动画效果
- Flask使用SocketIO实现WebSocket与Vue进行实时推送
- vue+flv.js+SpringBoot+websocket实现视频监控与回放功能
- vue项目中使用websocket的实现
- vue 项目中使用websocket的正确姿势
- vue实现websocket客服聊天功能
- Vue+Websocket简单实现聊天功能
- vue使用WebSocket模拟实现聊天功能
- websocket+Vuex实现一个实时聊天软件
- 使用WebSocket + SpringBoot + Vue 搭建简易网页聊天室的实现代码
