马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
新建WebSocketService.js
- export default class WebSocketService {
- constructor(url, getSocketMsg, sendSucc) {
- this.url = url;
- this.getSocketMsg = getSocketMsg;
- this.sendSucc = sendSucc; // 发送命令成功后的回调,可有可无
-
-
- this.socketTask = null;
- this.isOpenSocket = false;
- this.socketPrestore = {
- state: false,
- data: null
- };
- }
- connect() {
- this.socketTask = uni.connectSocket({
- url: this.url,
- success: ()=>{
- console.log('正在建立socket链接:', this.url);
- },
- });
- this.socketTask.onOpen(() => {
- console.log("WebSocket连接已发开...!");
- this.isOpenSocket = true;
-
- if (this.socketPrestore.state) {
- this.sendSocketData(this.socketPrestore.data);
- this.socketPrestore.state = false;
- }
- });
- this.socketTask.onMessage((res)=>{
- this.getSocketMsg(res)
- });
- this.socketTask.onClose(() => {
- this.isOpenSocket = false;
- });
- };
- sendSocketData(data) {
- if (this.isOpenSocket) {
- const sendData = JSON.stringify(data);
- console.log("发送socket数据:", sendData);
- this.socketTask.send({
- data: sendData,
- success: ()=>{
- console.log("socket消息发送成功");
- this.sendSucc && this.sendSucc()
- }
- });
- } else {
- this.socketPrestore.data = data;
- this.socketPrestore.state = true;
- this.connect(this.url)
- }
- };
- close() {
- if (this.isOpenSocket) {
- this.socketTask.close();
- this.isOpenSocket = false;
- }
- }
- }
复制代码 关于socketPrestore 部门代码处理机制是根据我的业务添加的,防止发送命令的时间socket链接被服务主动断开做的机制处理,若不需要直接删除就行。
方法调用
- <script>
- //引入websocket文件
- import WebSocketService from '@/utils/WebSocketService.js'
- export default {
- data() {
- return {
- socket: null,
- }
- },
- mounted() {
- const url = 'wss://.....'// socket地址
- this.socket = new WebSocketService(url, this.receiveSocketData, this.sendSucc)
- },
- methods: {
- receiveSocketData(res){
- console.log('接收到socket数据:', res);
- },
- sendSucc(){
- console.log('发送命令成功后的回调');
- }
- }
- }
- </script>
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |