WebSocket学习笔记

1.

uniapp数据缓存

2.前端通信--H5提供的 webSocket

https://blog.csdn.net/weixin_41927760/article/details/96459597

3.uni-app中使用websocket

uni-app中使用websocket_uniapp连接websocket

4.uni-app使用websocket官方文档

uni.connectSocket(OBJECT) | uni-app官网 (dcloud.net.cn)

5.uniapp APP 端 WebSocket 使用,实现一个简单 WebSocket 工具类

uniapp APP 端 WebSocket 使用,实现一个简单 WebSocket 工具类

6.uni-app中使用webSocket实现消息监听

uni-app中使用webSocket实现消息监听

7..NET Core中WebSocket的使用详解

.NET Core中WebSocket的使用详解】【https://www.cnblogs.com/kklldog/p/core-for-websocket.html

案例代码:【GitHub - kklldog/CoreWebsocketChatRoom: Websocket chat room demo base on Asp.net core .

8.C#搭建高效、便捷的WebSocket服务器和客户端

C#搭建高效、便捷的WebSocket服务器和客户端

9.TouchSocket开源库【若汝棋茗 (RRQM_Home) - Gitee.com】【TouchSocket是.Net(包括 C# 、VB.Net、F#)的一个整合性的socket网络通信框架

10. ***.Net Core 实现WebSocket Server 的另外三种方式***

.Net Core 实现WebSocket Server 的另外三种方式_zls365365的博客-CSDN博客

WebSocketServerDemo2: .net core 实现websocket server 的 另外三种方式。

11..NET Core 实现基于Websocket的在线聊天室

.NET Core 实现基于Websocket的在线聊天室_dotNET跨平台的博客-CSDN博客

CoreWebsocketChatRoom源代码

<template>
	<view></view>
</template>
<script>
import WS from "util/websocket.js";
	export default {
		data() {
			return {
				timer: null,
			}
		},
		methods: {
			loadData(){
				this.showselect=this.showselect?false:true;
			}
		},
		onLoad(){
			const url = 'ws://192.168.1.112:5000' //域名端口同通信服务器
			const ws = new WebSocket(url);
			ws.onopen = () => { //初次连接
				ws.send('我进入了xxx的直播间');
			}
			ws.onmessage = msg => {
			var content = document.querySelector('#content')
				console.log(msg); //服务发送过来的消息
			}
		},
		onClose()
		{
			//console.log("关闭了");
		},
		destroyed()
		{
			clearInterval(this.timer);
			this.timer = null;
		},
		beforeDestroy() {
			clearInterval(this.timer);
			this.timer = null;
		},
		async onLoad() {
			this.loadData();
			this.timer = setInterval(() => {
			        this.loadData()
			    }, 1600);
		}
	}
</script>

<style lang="scss">
	.csstorage{
		border: 1.5px solid #C8C8C8;
		border-radius: 5px;
	}
</style>
// @/utils/utils.js

// ...

// 判断字符串是否为JSON格式
export function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj = JSON.parse(str);
            if (typeof obj == 'object' && obj) {
                return true;
            } else {
                return false;
            }

        } catch (e) {
            // console.log('error:'+str+'!!!'+e);
            return false;
        }
    }
    // console.log('It is not a string!')
}

// ...
// @/utils/websocket.js
import { isJSON } from "@/util/utils.js"

class WebSocketClass {
  constructor(url) {
    this.lockReconnect = false;  // 是否开始重连
    this.wsUrl = "";  // ws 地址
    this.globalCallback = null;  // 回调方法
    this.userClose = false;  // 是否主动关闭
    this.createWebSocket(url);
  }

  createWebSocket(url) {
    // #ifdef H5
    if (typeof (WebSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
      return false
    }
    // #endif

    // #ifdef APP-PLUS
    if (typeof (uni.connectSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
      return false
    }
    // #endif

    this.wsUrl = url;
    try {
      // 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】

      // #ifdef H5
      this.ws = new WebSocket(this.wsUrl);
      this.initEventHandle();
      // #endif

      // #ifdef APP-PLUS
      this.ws = uni.connectSocket({
        url: this.wsUrl,
        success(data) {
          console.log("websocket连接成功");
          
          this.initEventHandle();
        },
      });
      // #endif
    } catch (e) {
      this.reconnect(url);
    }
  }

  // 初始化
  initEventHandle() {
    /**
     * 监听WebSocket连接打开成功
     */

    // #ifdef H5
    this.ws.onopen = (event) => {
      console.log("WebSocket连接打开");
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onOpen(res => {
      console.log('WebSocket连接打开'); 
    });
    // #endif

    
    /**
     * 连接关闭后的回调函数
     */

    // #ifdef H5
    this.ws.onclose = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onClose(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif
    

    /**
     * 报错时的回调函数
     */ 

    // #ifdef H5
    this.ws.onerror = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onError(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif


    /**
     * 收到服务器数据后的回调函数
     */ 
    
    // #ifdef H5
    this.ws.onmessage = (event) => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)
        
        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onMessage(event => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)

        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    });
    // #endif
  }

  // 关闭ws连接回调
  reconnect(url) {
    if (this.lockReconnect) return;
    this.ws.close();
    this.lockReconnect = true;  // 关闭重连,没连接上会一直重连,设置延迟避免请求过多
    setTimeout(() => {
      this.createWebSocket(url);
      this.lockReconnect = false;
    }, 1000);
  }

  // 发送信息方法
  webSocketSendMsg(msg) {
    this.ws && this.ws.send({
      data: msg,
      success() {
        console.log("消息发送成功");
      },
      fail(err) {
        console.log("关闭失败", err)
      }
    });
  }

  // 获取ws返回的数据方法
  getWebSocketMsg(callback) {
    this.globalCallback = callback
  }

  // 关闭ws方法
  closeSocket() {
    if (this.ws) {
      this.userClose = true;
      this.ws.close({
        success(res) {
          console.log("关闭成功", res)
        },
        fail(err) {
          console.log("关闭失败", err)
        }
      });
    }
  }

  writeToScreen(massage) {
    console.log(massage);
  }
}
export default WebSocketClass;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值