阮一峰WebSocket 入门教程
一般来说,wss接收域名 ws接收ip
方法一
调用时只需调用 this.initWebSocket() 即可,this.websock 上绑定的其他方法都是自调用的
<script>
export default {
created(){
// 调用获取实时数据
this.initWebSocket()
},
methods: {
initWebSocket() {
this.websock = null;
//判断当前浏览器是否支持WebSocket
if ("WebSocket" in window) {
//初始化weosocket(必须)
this.websock = new WebSocket(
"ws://172.23.126.15/audshow/websocket"
); //新建一个webstock对象
this.websock.onopen = this.websocketonopen;
this.websock.onmessage = this.websocketonmessage;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
} else {
alert("当前浏览器 Not support websocket");
}
},
websocketonopen() {
console.log("---连接建立成功---");
//websocket连接后发送数据(send发送)
// let actions = { 你要发送给后台的参数 }; //请根据实际项目需要进行修改
// this.websocketsend(JSON.stringify(actions));
},
websocketonerror() {
//连接建立失败重连
this.initWebSocket();
},
websocketonmessage(e) {
//数据接收
this.redata = JSON.parse(e.data).data;
console.log("-----redata-----")
console.log(this.redata);
},
websocketsend(Data) {
//数据发送
this.websock.send(Data);
},
websocketclose(e) {
//关闭
console.log("断开连接", e);
}
}
}
</script>
方法二
写入到一个方法中,调用时只需调用 receiveData() 即可,onopen() 等方法是自调用的
function receiveData() {
let socket;
var webSocketUrl = 'wss://jcxtm.chc.cn//vrserver/' + stationId + '/' + can_shu2;
// var webSocketUrl = 'ws://172.23.126.15/audshow/websocket';
if ('WebSocket' in window) {
socket = new WebSocket(webSocketUrl);
} else if ('MozWebSocket' in window) {
// socket = new MozWebSocket("wss://" + webSocketUrl + "/kg_fksc/portfolio2?param=web4k");
} else {
// socket = new SockJS("https://" + webSocketUrl + "/kg_fksc/sockjs/portfolio2?param=web4k");
}
/**
* 建立成功的回调函数
*/
socket.onopen = function () {
console.log("---连接建立成功---");
};
/**
* 服务器有消息返回的回调函数
*/
socket.onmessage = function (e) {
let msg = JSON.parse(e.data);
console.log(msg);
// 获取数据后写自己的数据处理逻辑
};
/**
* websocket链接关闭的回调函数
*/
socket.onclose = function () {
// receiveData();//websocket重连
};
}