1,websocket的基础使用方法
var ws = new WebSocket("wss://192.168.1.102:8080"); //需要连接的服务器端的URL 注意: ws或者wss一定要有 两者就是http协议和https协议的区别
ws.onopen:function() {
console.log("WebSocket连接成功");
ws.send("Hello WebSockets!"); //向服务器端发送数据的方法
};
ws.onmessage:function(e) {
console.log( "WebSocket推送的消息"); //发送完数据后,从服务器端接收相应返回的方法
};
ws.onerror:function (e) {
console.log("WebSocket连接发生错误");
},
ws.onclose:function (e) {
console.log("WebSocket断开连接");
},
2,websocket混入mixin用法
export const WebsocketMixin={ //创建mixin对象
mounted () {
this.initWebSocket();
},
destroyed: function () {
this.websocketOnclose(); // 离开页面生命周期函数
},
methods:{
...mapGetters(["userInfo"]),
initWebSocket(){
let url=`ws://47.92.242.71:9999/na/websocket/${this.userInfo().id}`
this.websock = new WebSocket(url);
this.websock.onopen = this.websocketOnopen;
this.websock.onerror = this.websocketOnerror;
this.websock.onmessage = this.websocketOnmessage;
this.websock.onclose = this.websocketOnclose;
},
websocketOnopen: function () {
console.log("WebSocket连接成功");
},
websocketOnerror: function (e) {
console.log("WebSocket连接发生错误");
this.reconnect();
},
websocketOnclose: function (e) {
this.reconnect();
console.log("WebSocket断开连接");
},
reconnect () {
var that = this;
if (that.lockReconnect) return;
that.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
setTimeout(function () {
console.info("尝试重连...");
that.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
},
}
//引入mixin对象直接调用即可
import { WebsocketMixin } from '@/assets/js/index/WebsocketMixin'
export default {
mixins: [WebsocketMixin],
data(){
return{
}
},
methods:{
// syl:socket推送信息
websocketOnmessage (e) {
console.log(e)
},
}
}
3,websocket和socket.io的区别
WebSocket是HTML5最新提出的规范,虽然主流浏览器都已经支持,但仍然可能有不兼容的情况,为了兼容所有浏览器,给程序员提供一致的编程体验,SocketIO将WebSocket、AJAX和其它的通信方式全部封装成了统一的通信接口,也就是说,我们在使用SocketIO时,不用担心兼容问题,底层会自动选用最佳的通信方式。因此说,WebSocket是SocketIO的一个子集