springboot websocket 简单入门
在没有WebSocket
时,大多时候我们在处理服务端主动给浏览器推送消息都是非常麻烦,且有很多弊端,如:
1.Ajax轮循
![](https://ask.qcloudimg.com/http-save/5427220/7uz5o2erl4.png?imageView2/2/w/1620)
优点:客户端很容易实现良好的错误处理系统和超时管理,实现成本与Ajax轮询的方式类似。
缺点:需要服务器端有特殊的功能来临时挂起连接。当客户端发起的连接较多时,服务器端会长期保持多个连接,具有一定的风险。
2. 基于 Iframe 及 htmlfile 的流(streaming)方式 俗称长连接。
![](https://ask.qcloudimg.com/http-save/5427220/ixmh6oszuu.png?imageView2/2/w/1620)
优点: 实时性好(消息延时小);性能好(能支持大量用户)
缺点: 长期占用连接,丧失了无状态高并发的特点。
今天我们就来说说WebSocket
。它是HTML5
开始提供的。
websocket方式
![](https://ask.qcloudimg.com/http-save/5427220/8w601n3i6c.png?imageView2/2/w/1620)
优点:
1、较少的控制开销。在连接创建后,服务器和客户端之间交换数据时,用于协议控制的数据包头部相对较小。在不包含扩展的情况下,对于服务器到客户端的内容,此头部大小只有2至10字节(和数据包长度有关);对于客户端到服务器的内容,此头部还需要加上额外的4字节的掩码。相对于HTTP请求每次都要携带完整的头部,此项开销显著减少了。
2、更强的实时性。由于协议是全双工的,所以服务器可以随时主动给客户端下发数据。相对于HTTP请求需要等待客户端发起请求服务端才能响应,延迟明显更少;即使是和Comet等类似的长轮询比较,其也能在短时间内更多次地传递数据。
3、保持连接状态。与HTTP不同的是,Websocket需要先创建连接,这就使得其成为一种有状态的协议,之后通信时可以省略部分状态信息。而HTTP请求可能需要在每个请求都携带状态信息(如身份认证等)。
4、更好的二进制支持。Websocket定义了二进制帧,相对HTTP,可以更轻松地处理二进制内容。
5、可以支持扩展。Websocket定义了扩展,用户可以扩展协议、实现部分自定义的子协议。如部分浏览器支持压缩等。
6、更好的压缩效果。相对于HTTP压缩,Websocket在适当的扩展支持下,可以沿用之前内容的上下文,在传递类似的数据时,可以显著地提高压缩率。
缺点:不支持低版本的IE浏览器
今天就和大家一起学习SpringBoot整合webSocket 一对一发送消息,一对多发送消息,服务器主动推送消息。
什么是webSocket?
对于上面的业务,我给大家画一个牛成图。hiahia~~ 可以参考看看哈。
![](https://ask.qcloudimg.com/http-save/5427220/3p48j17nhc.png?imageView2/2/w/1620)
不知道大家能不能看懂。再给大家写一个word版本的流程图:
![](https://ask.qcloudimg.com/http-save/5427220/9jl83k64wz.png?imageView2/2/w/1620)
好了,废话少说现在SpringBoot和WebSocket集成 上代码:
①、工程目录:
![](https://ask.qcloudimg.com/http-save/5427220/2gnbtbtvmc.png?imageView2/2/w/1620)
②、pom文件:
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.cnbuilder</groupId>
<artifactId>websocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>websocket</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<!--SpringBootWeb包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <!--webSocketjar-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency> <!--访问接口跳转templates目录下的html 必须加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<!--打包-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
③、webSocket配置文件:
WebSocketConfig:
package cn.cnbuilder.websocket.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration
public class WebSocketConfig { @Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
④、websocket连接信息配置:
ProductWebSocket: package cn.cnbuilder.websocket; import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap; /**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@ServerEndpoint("/websocket/{userId}")
@Component
public class ProductWebSocket { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户id
private static ConcurrentHashMap<String, ProductWebSocket> webSocketSet = new ConcurrentHashMap<String, ProductWebSocket>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session; //当前发消息的人员编号
private String userId = ""; /**
* 线程安全的统计在线人数
*
* @return
*/
public static synchronized int getOnlineCount() {
return onlineCount;
} public static synchronized void addOnlineCount() {
ProductWebSocket.onlineCount++;
} public static synchronized void subOnlineCount() {
ProductWebSocket.onlineCount--;
} /**
* 连接建立成功调用的方法
*
* @param param 用户唯一标示
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam(value = "userId") String param, Session session) {
userId = param;//接收到发送消息的人员编号
this.session = session;
webSocketSet.put(param, this);//加入线程安全map中
addOnlineCount(); //在线数加1
System.out.println("用户id:" + param + "加入连接!当前在线人数为" + getOnlineCount());
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userId.equals("")) {
webSocketSet.remove(userId); //根据用户id从ma中删除
subOnlineCount(); //在线数减1
System.out.println("用户id:" + userId + "关闭连接!当前在线人数为" + getOnlineCount());
}
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//要发送人的用户uuid
String sendUserId = message.split(",")[1];
//发送的信息
String sendMessage = message.split(",")[0];
//给指定的人发消息
sendToUser(sendUserId, sendMessage); } /**
* 给指定的人发送消息
*
* @param message
*/
public void sendToUser(String sendUserId, String message) { try {
if (webSocketSet.get(sendUserId) != null) {
webSocketSet.get(sendUserId).sendMessage(userId + "给我发来消息,消息内容为--->>" + message);
} else { if (webSocketSet.get(userId) != null) {
webSocketSet.get(userId).sendMessage("用户id:" + sendUserId + "以离线,未收到您的信息!");
}
System.out.println("消息接受人:" + sendUserId + "已经离线!");
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 管理员发送消息
*
* @param message
*/
public void systemSendToUser(String sendUserId, String message) { try {
if (webSocketSet.get(sendUserId) != null) {
webSocketSet.get(sendUserId).sendMessage("系统给我发来消息,消息内容为--->>" + message);
} else {
System.out.println("消息接受人:" + sendUserId + "已经离线!");
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 给所有人发消息
*
* @param message
*/
private void sendAll(String message) {
String sendMessage = message.split(",")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (!userId.equals(key)) {
webSocketSet.get(key).sendMessage("用户:" + userId + "发来消息:" + " <br/> " + sendMessage);
System.out.println("key = " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
} /**
* 发送消息
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
//同步发送
this.session.getBasicRemote().sendText(message);
//异步发送
//this.session.getAsyncRemote().sendText(message);
}
}
⑤、服务器推送接口:
IndexController:
package cn.cnbuilder.websocket.controller; import cn.cnbuilder.websocket.ProductWebSocket; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import java.util.Map;
import java.util.concurrent.TimeUnit; @Controller
public class IndexController { @GetMapping(value = "/")
@ResponseBody
public Object index() { return "Hello,ALl。This is yuanmayouchuang webSocket demo!";
} @ResponseBody
@GetMapping("test")
public String test(String userId, String message) throws Exception {
if (userId == "" || userId == null) {
return "发送用户id不能为空";
}
if (message == "" || message == null) {
return "发送信息不能为空";
}
new ProductWebSocket().systemSendToUser(userId, message);
return "发送成功!";
} @RequestMapping(value = "/ws")
public String ws() {
return "ws";
} @RequestMapping(value = "/ws1")
public String ws1() {
return "ws1";
}
}
⑥:SpringBoot配置文件
application.yml:
#端口号
server:
port: 12006
⑦:动态banner:
banner.txt:
__ ____ ____ _______
\ \ / / \/ \ \ / / ____|
\ \_/ /| \ / |\ \_/ / |
\ / | |\/| | \ /| |
| | | | | | | | | |____
|_| |_| |_| |_| \_____|::猿码优创:websocket SpringBoot Demo 博客地址:www.cnbuilder.cn
⑧:前段代码:
ws.html:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket SpringBootDemo</title>
</head>
<body>
<!--userId:发送消息人的编号-->
<div>默认用户id:xiaoyou001(后期可以根据业务逻辑替换)</div> <br/><input id="text" type="text"/>
<input placeholder="请输入接收人的用户id" id="sendUserId"></input>
<button onclick="send()">发送消息</button>
<br/> <button onclick="closeWebSocket()">关闭WebSocket连接</button>
<br/>
<div>公众号:猿码优创</div>
<br/>
<div id="message"></div>
</body> <script type="text/javascript">
var websocket = null; var userId = "xiaoyou001" //判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:12006/websocket/" + userId);
}
else {
alert('当前浏览器不支持websocket哦!')
} //连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
}; //连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
} //接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
} //连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
} //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
} //将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
} //关闭WebSocket连接
function closeWebSocket() {
websocket.close();
} //发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容 if (message == "") {
alert("发送信息不能为空!")
return;
} //获取发送人用户id
var sendUserId = document.getElementById('sendUserId').value;
if (sendUserId == "") {
alert("发送人用户id不能为空!")
return;
} document.getElementById('message').innerHTML += (userId + "给" + sendUserId + "发送消息,消息内容为---->>" + message + '<br/>');
message = message + "," + sendUserId//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
websocket.send(message);
}
</script>
</html> ws1.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<title>WebSocket SpringBootDemo</title>
</head>
<body>
<!--userId:发送消息人的编号-->
<div>默认用户id:xiaoyou002(后期可以根据业务逻辑替换)</div> <br/><input id="text" placeholder="请输入要发送的信息" type="text"/>
<input placeholder="请输入接收人的用户id" id="sendUserId"></input>
<button onclick="send()">发送消息</button>
<br/> <button onclick="closeWebSocket()">关闭WebSocket连接</button>
<br/>
<div>公众号:猿码优创</div>
</br>
<div id="message"></div>
</body> <script type="text/javascript">
var websocket = null; var userId = "xiaoyou002" //判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:12006/websocket/" + userId);
}
else {
alert('当前浏览器不支持websocket哦!')
} //连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket连接发生错误");
}; //连接成功建立的回调方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket连接成功");
} //接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
} //连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket连接关闭");
} //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
} //将消息显示在网页上
function setMessageInnerHTML(sendMessage) {
document.getElementById('message').innerHTML += sendMessage + '<br/>';
} //关闭WebSocket连接
function closeWebSocket() {
websocket.close();
} //发送消息
function send() {
var message = document.getElementById('text').value;//要发送的消息内容 if (message == "") {
alert("发送信息不能为空!")
return;
} //获取发送人用户id
var sendUserId = document.getElementById('sendUserId').value;
if (sendUserId == "") {
alert("发送人用户id不能为空!")
return;
} document.getElementById('message').innerHTML += ("我给" + sendUserId + "发送消息,消息内容为---->>" + message + '<br/>');
message = message + "," + sendUserId//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁
websocket.send(message);
}
</script>
</html>
测试:启动项目
![](https://ask.qcloudimg.com/http-save/5427220/isgf8a63rs.png?imageView2/2/w/1620)
首页访问地址:http://127.0.0.1:12006/
![](https://ask.qcloudimg.com/http-save/5427220/9w79m0e48j.png?imageView2/2/w/1620)
访问WebSocket测试页面1:http://127.0.0.1:12006/ws
![](https://ask.qcloudimg.com/http-save/5427220/v2rysxclly.png?imageView2/2/w/1620)
访问流程图:
![](https://ask.qcloudimg.com/http-save/5427220/dey6k0mwvo.png?imageView2/2/w/1620)
测试一对一发送消息:给另一个用户发送信息
换一个浏览器,测试两个 不要用同一浏览器,要不会出问题。
访问WebSocket测试页面2:http://127.0.0.1:12006/ws1
![](https://ask.qcloudimg.com/http-save/5427220/9ynkzl1rg3.png?imageView2/2/w/1620)
一对一发送消息牛成图:
![](https://ask.qcloudimg.com/http-save/5427220/qpc9ykdwkn.png?imageView2/2/w/1620)
测试服务器主动向浏览器推送消息:http://127.0.0.1:12006/test?userId=xiaoyou002&message=我是小优,听到请回答。
接口地址:http://127.0.0.1:12006/test
参数:userId:推送人用户id ws.html :xiaoyou001 ws1.html:xiaoyou002 写死的,可根据业务动态写活。
![](https://ask.qcloudimg.com/http-save/5427220/cw1yw3q9dv.png?imageView2/2/w/1620)
一对多推送的话:流程和一对一相似。大家自行研究哈。
/**
* 给所有人发消息
*
* @param message
*/
private void sendAll(String message) {
String sendMessage = message.split(",")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (!userId.equals(key)) {
webSocketSet.get(key).sendMessage("用户:" + userId + "发来消息:" + " <br/> " + sendMessage);
System.out.println("key = " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是websocket一对一发送消息,一对多发送消息,服务器主动推送消息 感觉是不是超简单!
文章摘自:https://cloud.tencent.com/developer/article/1474265
https://blog.lqdev.cn/2018/08/14/springboot/chapter-nineteen/
另备注另一种实现方法:https://blog.csdn.net/Ouyzc/article/details/79994401
https://docs.spring.io/spring/docs/5.0.8.RELEASE/spring-framework-reference/web.html#websocket
springboot websocket 简单入门的更多相关文章
- Java Springboot webSocket简单实现,调接口推送消息到客户端socket
Java Springboot webSocket简单实现,调接口推送消息到客户端socket 后台一般作为webSocket服务器,前台作为client.真实场景可能是后台程序在运行时(满足一定条件 ...
- websocket简单入门
今天说起及时通信的时候,突然被问到时用推的方式,还是定时接受的方式,由于之前页面都是用传统的ajax处理,可能对ajax的定时获取根深蒂固了,所以一时之间没有相同怎么会出现推的方式呢?当被提及webs ...
- SpringBoot之简单入门
一,spring boot 是什么? spring boot的官网是这样说的: Spring Boot makes it easy to create stand-alone, production- ...
- poi整合springboot超简单入门例子
1.导入依赖 2.application.properties只需要数据库连接信息就可以 3.目录结构 有个没用的service,请忽略 4.Controller,因为入门列子,所以简单的导出 导入读 ...
- 统一日志监控系统 springboot websocket 简单版 王代军-作品
http://git.oschina.net/redArmy/springboot-websocket-logs 目的: 统一监控 开发测试环境日志 如果需要可以拓展线上环境的日志(自己视情况而定) ...
- springboot 学习之路 1(简单入门)
目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...
- SpringBoot+SpringData 整合入门
SpringData概述 SpringData :Spring的一个子项目.用于简化数据库访问,支持NoSQL和关系数据存储.其主要目标是使用数据库的访问变得方便快捷. SpringData 项目所支 ...
- SpringBoot 搭建简单聊天室
SpringBoot 搭建简单聊天室(queue 点对点) 1.引用 SpringBoot 搭建 WebSocket 链接 https://www.cnblogs.com/yi1036943655/p ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...
随机推荐
- 使用ngspice进行电路仿真
电路spice仿真工具已经比较成熟,开源的免费工具也有不错的性能.使用ngspice可以得到不错的仿真结果. 在Linux系统上,例如写一个RLC谐振的电路: RLCV1 1 0 AC 1V L 1 ...
- FreeRTOS队列操作
API函数 //创建 #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) #define xQueueCreate( uxQueueLength, uxItemS ...
- 动态修改app build版本CFBundleVersion
1.需求说明 2.操作步骤 2.1 新建脚本,选择Build Phases 2.2 点击加号,选择New Run Script Phase 2.3 为了便于识别,双击重命名为 Dynamic Buil ...
- MySQL Network--域名与VIP
VIP与域名1.域名能在多个IDC切换,而VIP通常在特定网段内切换.2.VIP切换可以立即生效,而域名切换存在一定时间延迟. DNS解析顺序:1.查询本地域名映射配置(/etc/hosts)2.查查 ...
- h3c 802.11协议的发展进程
- Flask的基础二
一.session 除请求对象之外,还有一个 session 对象.它允许你在不同请求间存储特定用户的信息.它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需 ...
- Linux命令——dmesg
参考:Linux kernel buffer ring Linux dmesg Command Tutorial for Beginners (5 Examples) 7 ‘dmesg’ Comman ...
- 怎么查看二进制文件内容?linux下nm命令告诉你!
linux下强大的文件分析工具 -- nm 什么是nm nm命令是linux下自带的特定文件分析工具,一般用来检查分析二进制文件.库文件.可执行文件中的符号表,返回二进制文件中各段的信息. 目标文件. ...
- css详解4
1.固定定位 固定定位,页面内容多,页面滚动起来,才能看到固定定位效果. 比如下面这个,随之滚动条滚动它一直在右边.比如固定导航栏,小广告,回到顶部,应用在这些地方.一直固定位置不变的. 首先让页面能 ...
- 2013.6.24 - OpenNE第四天
今天晚上跟师兄讨论,这那几篇论文,对于<领域多词表 达翻译对的自动抽取及其应用>那篇,我的感觉是跟实体识别不太吻合.他的大概意思就是先讲所有有可能的多词表达都找出来,然后在用C-value ...