WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

现在,很多网站为了实现推送技术,所用的技术都是 Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。

HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。

详细的WebSocket介绍请参考菜鸟教程WebSocket

因为近期所使用的技术栈为VUE和SpringBoot,因此此文章所用技术环境也为VUE以及SpringBoot下。

建议先在后端(SpringBoot)配置好WebSocket。

maven依赖(因为我的SpringBoot项目为2.0以上,会自动选择最优版本,因此此处没有带上版本号):


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

WebSocket配置类


@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} }

WebSocket操作类


WebSocket的向用户推送可以为向所有用户推送以及单点推送

@Component
@ServerEndpoint("/websocket/{shopId}")
//此注解相当于设置访问URL
public class WebSocket { private Session session; private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<String,Session>(); @OnOpen
public void onOpen(Session session, @PathParam(value="shopId")String shopId) {
this.session = session;
webSockets.add(this);
sessionPool.put(shopId, session);
System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
} @OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
} @OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
} // 此为广播消息
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
} // 此为单点消息
public void sendOneMessage(String shopId, String message) {
Session session = sessionPool.get(shopId);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
} }

在Controller中使用


@RestController
@RequestMapping("api")
public class TestController {
@Autowired
private WebSocket webSocket; @RequestMapping("/sendAllWebSocket")
public String test() {
webSocket.sendAllMessage("清晨起来打开窗,心情美美哒~");
return "websocket群体发送!";
} @RequestMapping("/sendOneWebSocket")
public String sendOneWebSocket() {
webSocket.sendOneMessage("DPS007", "只要你乖给你买条gai!");
return "websocket单人发送";
}
}

在前端中(VUE)使用WebSocket


当然不在vue中使用也是一样的,只不过要注意的是WebSocket在普通js中如何创建以及销毁

<script>
export default {
data() {
return {
shopId:''
}
},
created() { // 页面创建生命周期函数
this.initWebSocket()
},
destroyed: function () { // 离开页面生命周期函数
this.websocketclose();
},
methods: {
collapse: function(){
this.isCollapse = !this.isCollapse;
if (this.isCollapse) {
this.iconClass = "cebianlanzhankai";
} else{
this.iconClass = "cebianlanshouhui";
}
},
initWebSocket: function () {
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
this.websock = new WebSocket("ws://localhost:8046/websocket/DPS007");
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
},
websocketonopen: function () {
console.log("WebSocket连接成功");
},
websocketonerror: function (e) {
console.log("WebSocket连接发生错误");
},
websocketonmessage: function (e) {
var da = JSON.parse(e.data);
console.log(da);
this.message = da;
},
websocketclose: function (e) {
console.log("connection closed (" + e.code + ")");
}
}
}
</script>

原文地址:https://segmentfault.com/a/1190000017268973

WebSocket的使用(基于VUE与SpringBoot)的更多相关文章

  1. 基于Vue、Springboot网站实现第三方登录之QQ登录,以及邮件发送

    基于Vue.Springboot实现第三方登录之QQ登录 前言 一.前提(准备) 二.QQ登录实现 1.前端 2.后端 1.application.yml 和工具类QQHttpClient 2.QQL ...

  2. 前端基于vue,后台采用springboot+shiro的方式搭建的一个移动端商品展示平台

    基于vue实现的移动端商品展示页,可以web-view的方式嵌入到小程序中,布局简约.大气,减少初学者或开发者不必要的工作量.后台维护采用的springboot+shiro的方式,为广大爱好者提供展示 ...

  3. 基于Vue的SPA动态修改页面title的方法

    最近基于VUE做个SPA手机端web发现动态修改页面标题通过document.title=xxxx 来修改着实蛋疼,而且在IOS的微信端据说没效果.百度发现要针对IOS的微信做点额外的操作,即:创建一 ...

  4. 基于vue的分页插件

    相信大家用过很多jquery的分页插件,那这次就用一用基于vue的分页插件. 这里的环境用的是springboot 首先要引入pagehelper的jar文件,版本是1.2.3,配置文件也需要配置一下 ...

  5. 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建

    基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...

  6. 一次基于Vue.Js用户体验的优化

    .mytitle { background: #2B6695; color: white; font-family: "微软雅黑", "宋体", "黑 ...

  7. 发布自己第一个npm 组件包(基于Vue的文字跑马灯组件)

    一.前言 总结下最近工作上在移动端实现的一个跑马灯效果,最终效果如下: 印象中好像HTML标签的'marquee'的直接可以实现这个效果,不过 HTML标准中已经废弃了'marquee'标签 既然HT ...

  8. 基于vue的颜色选择器color-picker

    项目中有用到颜色选择器的童鞋们可以看过来了 关于color-picker的jquery的插件是有蛮多,不过vue组件没有吧,反正我没有找到, 虽然element-ui里面有这个,但是你愿意为了一个小功 ...

  9. 基于Vue实现后台系统权限控制

    原文地址:http://refined-x.com/2017/08/29/基于Vue实现后台系统权限控制/,转载请注明出处. 用Vue/React这类双向绑定框架做后台系统再适合不过,后台系统相比普通 ...

随机推荐

  1. PyCharm中Qt Designer+PyUIC配置

    本文环境配置: 系统=>windows10:64位 语言=>Python:3.7.1 第三方库PyQT5:5.11.3pyqt5-tools:5.11.3.1.4 工具=>PyCha ...

  2. Mybatis 结果映射下划线转驼峰

    mybatis 结果映射下划线转驼峰 Spring Boot 配置: #下划线转驼峰 mybatis.configuration.map-underscore-to-camel-case=true m ...

  3. python27 错误汇总

    一.TypeError: object of type 'NoneType' has no len() 解决的方法: 源代码:resp_data = None  (None是一个空的对象) 修改后代码 ...

  4. 分治NTT:我 卷 我 自 己

    感觉这种东西每次重推一遍怪麻烦的,就写在这里了. 说白了就是根据分治区间左端点是否为\(0\)分类讨论一下,一般是如果不是\(0\)就要乘\(2\),不过还是需要具体问题具体分析一下才好(就比如下面的 ...

  5. vi 学习

    1,光标移动 1)h:左:l:右:j:下:k:上:和方向键不同的是,不会造成折行 2)0:行首:$行尾:G:最后一行第一个字符;gg:第一行第一个字符:^:本行第一个非空白字符:H:移至屏幕第一个字符 ...

  6. Windows下如何安装Redis

    Redis可以从下面的github上面下载,当前的下载版本为3.2.100版本 https://github.com/MicrosoftArchive/redis/releases 这边都是64位的链 ...

  7. var $this = $(this)

    jQuery: What’s the Difference Between $(this), $this, and this? What about $this? $this is a little ...

  8. PHP CI框架数据库常用操作

    例子 <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Menu extends CI_Co ...

  9. 【转】C++友元

    转自:https://www.cnblogs.com/BeyondAnyTime/archive/2012/06/04/2535305.html 1.友元函数的简单介绍 1.1为什么要使用友元函数 在 ...

  10. 常用IDE 教程(IntelliJ IDEA、Android Studio、Chrome)

    1.IntelliJ IDEA 使用教程 http://wiki.jikexueyuan.com/project/intellij-idea-tutorial/ 2.Chrome 开发工具指南 htt ...