springboot+websocket 归纳收集
websocket是h5后的技术,主要实现是一个长连接跟tomcat的comet技术差不多,但websocket是基于web协议的,有更广泛的支持。当然,在处理高并发的情况下,可以结合tomcat的asyncContext来实现长处理的异步返回等操作。
1.引入依赖类
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.</version>
</dependency> <!-- websocket dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
这里主要是引入websocket的依赖类
2.springboot配置websocket的入口bean
在springboot的配置类下,引入以下的配置bean
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
3.实现websocket的后端处理逻辑
package com.ouyang.server; import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet; /**
* Created by Administrator on 2018/3/25.
*/ //@Slf4j
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer { Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = ;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
// 备用的同步hashmap
//private static ConcurrentHashMap<Session,WebSocketServer> webSocketServerConcurrentHashMap = new ConcurrentHashMap(); //与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session; /**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新连接加入!当前在线人数为" + getOnlineCount());
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
// //连接打开时执行
// @OnOpen
// public void onOpen(@PathParam("user") String user, Session session) {
// currentUser = user;
// System.out.println("Connected ... " + session.getId());
// } /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("来自客户端的消息:" + message); //群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage("response message:"+message);
} catch (IOException e) {
e.printStackTrace();
}
}
//单发的信息
sendMessage("currentWebsocket is ok!!! ");
} /**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
} /**
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
} /**
* 群发自定义消息
* */
public static void sendInfo(String message) throws IOException {
//log.info(message);
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
} public static synchronized int getOnlineCount() {
return onlineCount;
} public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
} public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
至此,我们关于后台的websocket的主要实现类都实现了,接下来我们可以弄一个,测试的接口,用于给所有的websocket推送信息,如下:
@RequestMapping(value="/publicSend",method= RequestMethod.GET)
@ResponseBody
public String pushVideoListToWeb2(String id) {
try {
WebSocketServer.sendInfo("有新客户呼入,sltAccountId:"+id);
for(int i= ;i<;i++){
WebSocketServer.sendInfo("有新客户呼入,testing:"+String.valueOf(i));
}
}catch (IOException e) { }
return "success!"; }
4.前端测试页面的实现
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.springframework.org/schema/jdbc">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/jquery.js"></script>
<script src="/static/stomp.min.js"></script>
<script src="/static/sockjs.min.js"></script>
<script>
//socket = new WebSocket("ws://localhost:8081/begenstom/websocket");
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
console.log("您的浏览器支持WebSocket"); //实现化WebSocket对象,指定要连接的服务器地址与端口
//socket = new WebSocket("ws://localhost:9094/starManager/websocket/张三");
socket = new WebSocket("ws://localhost:8081/websocket");
//打开事件
socket.onopen = function () {
console.log("Socket 已打开");
for (var i=;i<;i++)
{
socket.send("这是来自客户端的消息1:" + i);
}
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//发现消息进入 调后台获取
document.write(msg.data);
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
}
$(window).unload(function () {
socket.close();
});
}
</script> </head>
<body> </body>
</html>
这里主要用到3个js,可以去github上去当一个。
测试结果:==================

参考地址:
* https://blog.csdn.net/zhangdehua678/article/details/78913839
* https://github.com/ayman-elgharabawy/Kafka-SpringBoot-WebSocket
* 整合框架 https://github.com/527515025/springBoot
springboot+websocket 归纳收集的更多相关文章
- SpringBoot+WebSocket
SpringBoot+WebSocket 只需三个步骤 导入依赖 <dependency> <groupId>org.springframework.boot</grou ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...
- SpringBoot WebSocket STOMP 广播配置
目录 1. 前言 2. STOMP协议 3. SpringBoot WebSocket集成 3.1 导入websocket包 3.2 配置WebSocket 3.3 对外暴露接口 4. 前端对接测试 ...
- Java Springboot webSocket简单实现,调接口推送消息到客户端socket
Java Springboot webSocket简单实现,调接口推送消息到客户端socket 后台一般作为webSocket服务器,前台作为client.真实场景可能是后台程序在运行时(满足一定条件 ...
- Springboot+Websocket+JWT实现的即时通讯模块
场景 目前做了一个接口:邀请用户成为某课程的管理员,于是我感觉有能在用户被邀请之后能有个立马通知他本人的机(类似微博.朋友圈被点赞后就有立马能收到通知一样),于是就闲来没事搞了一套. 涉及技术栈 ...
- Springboot+websocket+定时器实现消息推送
由于最近有个需求,产品即将到期(不同时间段到期)时给后台用户按角色推送,功能完成之后在此做个小结 1. 在启动类中添加注解@EnableScheduling package com.hsfw.back ...
- springboot websocket 一篇足够了
什么是WebSocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 … 为什么要实现握手监控管理 如果说,连接随意创建,不管的话,会存在错误,broken pipe 表面看单纯报 ...
- SpringBoot + WebSocket 开发笔记
1. 服务端的实现,我尝试了两种方式: 第一种是用“@ServerEndPoint”注解来实现,实现简单: 第二种稍显麻烦,但是可以添加拦截器在WebSocket连接建立和断开前进行一些额外操作. 不 ...
- springBoot -webSocket 基于STOMP协议交互
浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打破了 ...
随机推荐
- 结对项目-四则运算"软件"之升级版
本次作业要求来自:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/2213 github地址为:https://github.com/L ...
- WebSocket实现简单的在线聊天
SuperWebSocket在WebService中的应用 最开始使用是寄托在IIS中,发布之后测试时半个小时就会断开,所以改为WindowsService 1. 新建Windows服务项目[Test ...
- maven(一):是否有必要使用maven
以下是普通项目和maven项目 分别引入spring core模块的区别 1,假设我们有十个项目,都需要引入spring core模块,那么需要十份重复的Spring core.jar和commons ...
- 洗礼灵魂,修炼python(60)--爬虫篇—httplib2模块
这里先要补充一下,Python3自带两个用于和HTTP web 服务交互的标准库(内置模块): http.client 是HTTP协议的底层库 urllib.request 建立在http.clien ...
- [cb]ScriptableWizard 创建向导
需求 方便策划一步一步的创建Actor 思路分析 Unity的Editor中提供创建向导的功能,ScriptableWizard 代码实现 创建一个WizardCreateActor继承自Script ...
- systemd 和 如何修改和创建一个 systemd service (Understanding and administering systemd)
系统中经常会使用到 systemctl 去管理systemd程序,刚刚看了一篇关于 systemd 和 SysV 相关的文章,这里简要记录一下: systemd定义: (英文来解释更为原汁原味) sy ...
- Scrapy爬取遇到的一点点问题
学了大概一个月Scrapy,自己写了些东东,遇到很多问题,这几天心情也不大好,小媳妇人也不舒服,休假了,自己研究了很久,有些眉目了 利用scrapy 框架爬取慕课网的一些信息 步骤一:新建项目 scr ...
- SAP UI 搜索分页技术
搜索分页技术往往和另一个术语Lazy Loading(懒加载)联系起来.今天由Jerry首先介绍S/4HANA,CRM Fiori和S4CRM应用里的UI搜索分页的实现原理.后半部分由SAP成都研究院 ...
- CF 633 E. Binary Table
题目链接 题目大意:给定一个棋盘,棋盘上有0或1,你可以将一整行取反或者一整列取反,要使得最后剩的1最少.\((1\le n\le 20,1\le m\le 100000)\). 一个容易想到的思路就 ...
- c++のurlmon实现下载文件并进度回调
主文件: #include "stdafx.h" #include <UrlMon.h> #pragma comment(lib, "urlmon.lib&q ...