一、websocket
【前端WebSocket的使用 (超详细)】_前端websocket怎么用-优快云博客
socket前端使用方法,封装js_前端socket-优快云博客
initWebsocket() {
this.socket = new WebSocket("ws://192.168.1.15:24836/websocket/message");
// 添加WebSocket事件监听器
console.log(this.socket);
this.socket.onopen = () => {
console.log("WebSocket连接已建立");
};
this.socket.onmessage = (event) => {
const message = event.data;
console.log("Received message:", message);
// 根据接收到的消息内容来决定要走哪个接口
if (message === "132") {
// 调用接口1的逻辑
}
};
this.socket.onerror = (error) => {
console.error("WebSocket error:", error);
// 处理错误
this.initWebsocket();
};
this.socket.onclose = () => {
console.log("WebSocket连接已关闭");
// 处理连接关闭
this.initWebsocket();
};
},
mounted() {
this.initWebsocket();
},
3.给服务端发送消息
// 在某个Vue组件中
//我们定义了一个sendParamsToServer方法,接受两个参数param1和param2。我们将这两个参数组装成一个对象,并使用JSON.stringify()将对象转换为字符串,然后将这个字符串作为消息发送给服务器。
export default {
methods: {
sendParamsToServer(param1, param2) {
// 将要传递的参数编码为字符串,这里使用JSON格式
const params = {
param1: param1,
param2: param2,
};
const message = JSON.stringify(params);
// 发送数据到服务器
this.$socket.send(message);
},
},
};
当我们在WebSocket通信中发送参数,参数值可能代表着不同的指令或操作类型。以下是一个更清晰的例子
// 假设这部分代码在一个Vue组件中 // 导入WebSocket模块(假设已经建立连接并将WebSocket对象添加到Vue的原型中)
import Vue from 'vue';
export default {
methods: {
fetchData() {
// 发送指令给服务器:获取数据
this.sendCommandToServer('get-data');
},
sendData() {
// 发送指令给服务器:发送数据
this.sendCommandToServer('send-data');
},
updateData() {
// 发送指令给服务器:更新数据
this.sendCommandToServer('update-data');
},
sendCommandToServer(command) {
// 将指令封装为一个对象
const message = JSON.stringify({
command: command,
});
// 发送数据到服务器
this.$socket.send(message);
},
},
};
当在不同的页面中根据传递的指令执行不同的接口时,可以通过在WebSocket通信中传递额外的参数来实现。这样服务器端就可以根据这些参数来识别不同的指令,从而执行相应的接口逻辑。
//WebSocketComponent.vue
//在这个WebSocketComponent.vue组件中,我们定义了sendCommandToServer方法,该方法接受两个参数:command和data。command参数表示指令,data参数表示附加的数据。我们将这两个参数封装为一个对象,并将这个对象转换为JSON格式的字符串,然后发送给服务器。
<template>
<!-- 这里可以放置WebSocket相关的代码 -->
</template>
<script>
export default {
methods: {
sendCommandToServer(command, data) {
// 将指令和数据封装为一个对象
const message = JSON.stringify({
command: command,
data: data,
});
// 发送数据到服务器
this.$socket.send(message);
},
},
};
</script>
以下是两个示例页面的代码: Page1.vue
//Page1.vue:通过引用WebSocketComponent.vue组件,并调用sendCommandToServer方法来发送指令和数据
<template>
<div>
<button @click="fetchData">获取数据</button>
<!-- 其他页面1的内容 -->
</div>
</template>
<script>
import WebSocketComponent from './WebSocketComponent.vue';
export default {
components: {
WebSocketComponent,
},
methods: {
fetchData() {
// 在Page1页面中调用sendCommandToServer方法,发送获取数据的指令,并附带数据
this.$refs.webSocketComponent.sendCommandToServer('get-data', { type: 'example' });
},
},
};
</script>
Page2.vue:
//Page2.vue:在Page1.vue和Page2.vue页面中,我们分别引用了WebSocketComponent.vue组件,并在点击按钮时调用了sendCommandToServer方法。我们分别传递了不同的指令和附带的数据,这样服务器端就可以根据接收到的指令和数据来执行不同的接口逻辑。
<template>
<div>
<button @click="sendData">发送数据</button>
<!-- 其他页面2的内容 -->
</div>
</template>
<script>
import WebSocketComponent from './WebSocketComponent.vue';
export default {
components: {
WebSocketComponent,
},
methods: {
sendData() {
// 在Page2页面中调用sendCommandToServer方法,发送发送数据的指令,并附带数据
this.$refs.webSocketComponent.sendCommandToServer('send-data', { value: 42 });
},
},
};
</script>
心跳机制,断开重连(上面是只在onclose和onerro里面进行重新init),或者发生错误就thissocket=null;监听socket,没有就重调用init
websocket的基础使用,心跳机制,断线重连_websocket断开后怎么自动连接-优快云博客
用这个
websocket.vue
<template></template>
<script>
export default {
props: {
url: {
type: String,
required: true,
},
},
data() {
return {
// url: "ws://127.0.0.1:8080/websocket/message",
// url: "ws://75jvir.natappfree.cc/websocket/message",
// url: "ws://10.39.176.69:8080/websocket/message",
message: "",
text_content: "",
ws: null,
};
},
watch: {},
methods: {
join() {
const wsuri = this.url;
this.ws = new WebSocket(wsuri);
const self = this;
this.ws.onopen = function (event) {
self.text_content = self.text_content + "已经打开连接!" + "\n";
console.log("已经打开连接");
};
this.ws.onmessage = function (event) {
self.text_content = event.data + "\n";
self.$emit("changeShovel", event.data);
};
this.ws.onclose = function (event) {
console.log("已经关闭连接");
self.text_content = self.text_content + "已经关闭连接!" + "\n";
};
},
// 停止
exit() {
if (this.ws) {
this.ws.close();
this.ws = null;
}
},
// 发送
send() {
if (this.ws) {
this.ws.send(this.message);
} else {
alert("未连接到服务器");
}
},
},
mounted() {
this.join();
// this.ws.onopen;
// setInterval(() => {
// this.ws.close();
// }, 8000);
// 重连
const that = this;
setInterval(function () {
that.ws.readyState != 1 && that.join();
}, 10000);
},
destroyed() {
this.exit();
},
};
</script>
页面引用
<websocket-vue
v-show="'false'"
@changeShovel="changeShovel"
:url="'ws://10.39.183.16:8080/websocket/message'"
/>
import WebsocketVue from "./websocketVue.vue";
components: {WebsocketVue },
1.后端定时推送socket数据,但是前端有下拉切换传参,就不行
原因:后端推送,前端不能传参 (前端也不能主动传参过去然后后端实时推数据,这样的话如果两台电脑都登陆系统并切换参数,最后一个参数就覆盖上一个了,最后数据传的都是最后一个参数!)
解决:前端实时调用普通接口并传参(用不用socket无关,每笔要用)
二、socket io
井工一矿+电铲
详解vue-socket.io使用教程与踩坑记录_vue.js_脚本之家#_lab2_2_0
https://www.youkuaiyun.com/tags/MtjaQgwsNDgyMzUtYmxvZwO0O0OO0O0O.html
(success:
public下的index.html:cdn引入:
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script> <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
var socket
socketIOconn () {
var userName = 'user' + Math.floor((Math.random() * 1000) + 1);
//创建通道连接 (url,参数:params:{ query:‘’,//连接参数 path: '/socket.io','force new connection': true //新开一个websocket连接})
// var socket = io.connect('/icon_sets/change', {query:"name=my_img_name"});
socket = io.connect(this.connectSrc + 'countTotal');
socket.on('connect', function () {
output('Client has connected to the server!');
});
socket.on('chatevent', function (message) {
output('' + message.userName + ': ' + message.message);
});
socket.on('homePageCount', (message) => {
this.statusData = message
// output('' + message.x + ': ' + message.y);
});
socket.on('disconnect', function () {
});
//关闭通道连接 可被@OnDisconnect注解的方法监听
function sendDisconnect () {
socket.disconnect();
}
function sendMessage () {
var message = $('#msg').val();
$('#msg').val('');
var jsonObject = {
userName: userName,
message: message
};
//发往后端@OnEvent("chatevent")注解的方法
socket.emit('chatevent', jsonObject);
}
function output (message) {
// var currentTime = "" + moment().format('HH:mm:ss.SSS') + "";
// var element = $("<div>" + currentTime + " " + message + "</div>");
// $('#console').prepend(element);
}
$(document).keydown(function (e) {
if (e.keyCode == 13) {
$('#send').click();
}
});
},
)
// success over
main.js中:
// socketio
import VueSocketIO from 'vue-socket.io'
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://192.168.0.198:9099?userId=79',
options: {
// 创建时是否自动连接 我们这里设定为false,在指定页面再开启
autoConnect: false,
// 路径(默认值:/socket.io/)
// path: "",
// 目前有两种传输方式:HTTP long-polling(可简称:polling)、WebSocket
transports: ['polling'],
// 附加请求头(在服务器端的 socket.handshake.headers 对象中找到)
extraHeaders: {},
// query: { userId: "robot111", }
},
// 如果没有使用到 store 可不写
vuex: {
store,
mutationPrefix: "SOCKET_",
actionPrefix: "SOCKET_"
}
}))
App.vue中:(使用的是this.$emit.)
sockets: {
//查看socket是否连接成功
connect () {
console.log("socket.io链接成功");
// 向服务端发消息
this.$socket.emit("ClientReceive", "socket.io连接成功后向后台发送消息");
},
disconnect () {
console.log("socket.io断开链接");
}, //检测socket断开链接
reconnect () {
console.log("socket.io重新链接");
},
// 心跳
users (data) {
console.log('在线人数', data);
},
// 后台推送数据
receive_message (data) {
console.log('接收数据', data);
},
// socket队列推送消息,在这个时间接收消息
transferMessage (data) {
console.log('运送消息', data);
},
//客户端接收后台传输的socket事件
ClientReceive (data) {
const messageData =
data.message == "hello client" ? "" : JSON.parse(data);
if (messageData) {
this.$elementMessage(messageData.content);
// 格式化消息时间戳
messageData.createTime = this.$utils.formatDateAll(
messageData.createTime
);
this.$store.dispatch("SOCKET_CONTENT_CHANGE", messageData);
}
console.log("--messageData", messageData); //接收的消息
}
// 调用 io,接收服务端发来的推送
// this.sockets.subscribe("ClientReceive", data => {
// console.log("ClientReceive", data);
// });
}
cdn方式:!!!!!!成功
详解vue-socket.io使用教程与踩坑记录_vue.js_脚本之家#_lab2_2_0