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. Mysql启动报错 The server quit without updating PID

    [root@db mysql]# service mysql restartMySQL server PID file could not be found![失败]Starting MySQL... ...

  2. Jmeter获取未来时间

    1.添加前置处理器:BeanShell PreProcessor import java.text.SimpleDateFormat; import java.util.Calendar; impor ...

  3. Java中的Unicode与码点

    Java中,可以用\uXXXX表示Unicode字符,例如String s = "\u00X1";XXXX必须为4位,因此码点为U+1D546的字符,需要用两个编码单元表示,例如S ...

  4. request.getAttribute()和request.getParameter()两个方法的区别

    request.getAttribute()获得的数据必须曾经有过setAttibute()过: 而request.getParameter()获得是客户端POST或者GET请求时所携带的参数的值 g ...

  5. 第九周学习总结&实验报告(7)

    完成火车站售票程序的模拟. 要求: (1)总票数1000张; (2)10个窗口同时开始卖票; (3) 卖票过程延时1秒钟; (4)不能出现一票多卖或卖出负数号票的情 况 实验代码: package y ...

  6. Android采用pm命令静默卸载应用

    卸载app的方式有多种,可以直接调用android系统的卸载程序,但是这样会调出android卸载提示框,问题就是真的不好看. 所以采用静默卸载的方式,避免弹出系统提示框. 方法一(调用系统卸载程序) ...

  7. 七、smarty--缓存的控制

    1.建议缓存 $smarty->cacheing = true; //设置为2是给每一个模板设置缓存 $smarty->setCacheDir(“”); 2.处理缓存的生命周期 $smar ...

  8. 多个swiper使用样式出了问题

    observer:true,//修改swiper自己或子元素时,自动初始化swiper observeParents:true,//修改swiper的父元素时,自动初始化swiper 不行直接设  w ...

  9. yum源相关

    yum软件仓库默认配置文件/etc/yum.conf,此文件定义了yum在线下载的rpm包存放位置及下载后是否保存. [root@localhost ~]# head /etc/yum.conf[ma ...

  10. vue项目如何部署到Tomcat中

    vue项目如何部署到Tomcat中 1,假设你要访问的项目名称为'hms' 2,在Tomcat的webapps下创建hms文件夹, 3,配置config/index.js文件,build: {} 选项 ...