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
    评论
springboot学习笔记 spring基础 Spring概述 Spring的简史 xml配置 注解配置 java配置 Spring概述 Spring的模块 核心容器CoreContainer Spring-Core Spring-Beans Spring-Context Spring-Context-Support Spring-Expression AOP Spring-AOP Spring-Aspects Messaging Spring-Messaging WEB Spring-Web Spring-Webmvc Spring-WebSocket Spring-Webmvc-Portlet 数据访问/集成(DataAccess/Intefration) Spring-JDBC Spring-TX Spring-ORM Spring-OXM Spring-JMS Spring的生态 Spring Boot Spring XD Spring Cloud Spring Data Spring Integration Spring Batch Spring Security Spring HATEOAS Spring Social Spring AMQP Spring Mobile Spring for Android Spring Web Flow Spring Web Services Spring LDAP Spring Session Spring项目快速搭建 Maven简介 Maven安装 Maven的pom.xml dependencies dependency 变量定义 编译插件 Spring项目的搭建 Spring Tool Suite https://spring.io/tools/sts/all IntelliJ IDEA NetBeans https://netbeans.org/downloads/ Spring基础配置 依赖注入 声明Bean的注解 @Component组件,没有明确的角色 @Service在业务逻辑层(service层) @Repository在数据访问层(dao层) @Controller在展现层(MVC→SpringMVC) 注入Bean的注解 @Autowired:Spring提供的注解 @Inject:JSR-330提供的注解 @Resource:JSR-250提供的注解 Java配置 @Configuration声明当前类是一个配置类 @Bean注解在方法上,声明当前方法的返回值为一个Bean AOP @Aspect 声明是一个切面 拦截规则@After @Before @Around PointCut JoinPoint Spring常用配置 Bean的Scope Singleton Prototype Request Session GlobalSession SpringEL和资源调用 注入普通字符 注入操作系统属性 注入表达式云算结果 注入其他Bean的属性 注入文件内容 注入网址内容 注入属性文件 Bean的初始化和销毁 Java配置方式 注解方式 Profile @Profile 通过设定jvm的spring.profiles.active参数 web项目设置在Servlet的context parameter中 事件Application Event 自定义事件,集成ApplicationEvent 定义事件监听器,实现ApplicationListener 使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值