springBoot 使用webSocket
本文(2019年6月18日 飞快的蜗牛博客)
有许多人走着走着,就迷失了自己,所以不论发生了什么,有时候抱着自己去静下来想想,要好好的对待自己;“钱塘江上潮信来,今日方知我是我”,我信奉这句话,不是我超脱了,是有时我们醒悟了;
注意标题:springboot使用websocket
1】第一步:引入依赖:
<!--集成websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2】第二步:配置websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
*
* 使用@SpringBootApplication启动类进行启动时需要下面这段代码,****但生成war包部署在tomcat中不需要这段
* 若打成war包使用tomcat运行的话,则注释掉这个类中serverEndpointExporter 方法.
*
*/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3】第三步:可以在controller 下写下此类:
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
* 即时通讯
*/
@Component
@ServerEndpoint("/webSocket")
public class MyWebScoketController {
private static int onlineCount = 0;
private static CopyOnWriteArraySet<MyWebScoketController> webSocketSet = new CopyOnWriteArraySet<MyWebScoketController>();
private Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//群发消息
for(MyWebScoketController item: webSocketSet){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
@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);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebScoketController.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebScoketController.onlineCount--;
}
}
4】第四步:在前端写个公共myWebsocket.js 如下
if("WebSocket" in window){
console.log("this browser supports websocket...");
var webSocket=new WebSocket("ws://"+window.location.host+"/XXXX/webSocket");
}else{
console.log("this browser does not supports websocket...");
}
webSocket.onerror=function(){
console.log("链接错误...");
}
webSocket.onopen=function(){
console.log("链接成功...");
}
/*
* 哪个页面使用哪个页面加
* webSocket.onmessage=function(event){
alert(event);
}*/
webSocket.onclose=function(){
console.log("链接关闭...");
}
window.onbeforeunload=function(){
console.log("窗口即将关闭,准备关闭链接...");
webSocket.close();
}
function webSend(){
webSocket.send(decodeURIComponent($("#form1").serialize(),true));
}
function SendMesaage(mes){
webSocket.send(mes);
}
var closeConn=function(){
webSocket.close();
}
5】第五步:测试 现在页面引入
<script type="text/javascript" src="static/js/common/myWebSocket.js"></script>
在发送消息端写下:
SendMesaage(1300);
接收端写下:
webSocket.onmessage=function(event){
此处可以接收到消息
}
如果对你有用,觉得好可以给小编打个赏:

springBoot 使用webSocket的更多相关文章
- Springboot整合Websocket遇到的坑
Springboot整合Websocket遇到的坑 一.使用Springboot内嵌的tomcat启动websocket 1.添加ServerEndpointExporter配置bean @Confi ...
- SpringBoot 整合 WebSocket
SpringBoot 整合 WebSocket(topic广播) 1.什么是WebSocket WebSocket为游览器和服务器提供了双工异步通信的功能,即游览器可以向服务器发送消息,服务器也可以向 ...
- SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送
代码全部复制,仅供自己学习用 1.环境搭建 因为在上一篇基于STOMP协议实现的WebSocket里已经有大概介绍过Web的基本情况了,所以在这篇就不多说了,我们直接进入正题吧,在SpringBoot ...
- SpringBoot基于websocket的网页聊天
一.入门简介正常聊天程序需要使用消息组件ActiveMQ或者Kafka等,这里是一个Websocket入门程序. 有人有疑问这个技术有什么作用,为什么要有它?其实我们虽然有http协议,但是它有一个缺 ...
- springboot整合websocket原生版
目录 HTTP缺点 HTTP websocket区别 websocket原理 使用场景 springboot整合websocket 环境准备 客户端连接 加入战队 微信公众号 主题 HTTP请求用于我 ...
- 使用springboot+layim+websocket实现webim
使用springboot+layim+websocket实现webim 小白技术社 项目介绍 采用springboot和layim构建webim,使用websocket作为通讯协议,目前已经能够正 ...
- SpringBoot+Vue+WebSocket 实现在线聊天
一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二 ...
- springboot集成websocket的两种实现方式
WebSocket跟常规的http协议的区别和优缺点这里大概描述一下 一.websocket与http http协议是用在应用层的协议,他是基于tcp协议的,http协议建立链接也必须要有三次握手才能 ...
- springboot集成websocket实现向前端浏览器发送一个对象,发送消息操作手动触发
工作中有这样一个需示,我们把项目中用到代码缓存到前端浏览器IndexedDB里面,当系统管理员在后台对代码进行变动操作时我们要更新前端缓存中的代码怎么做开始用想用版本方式来处理,但这样的话每次使用代码 ...
随机推荐
- Mybatis-04-分页
分页 思考:为什么要分页? 减少数据的处理量 1 使用limit分页 select * from user limit startIndex,pageSize;
- 分治算法(二分查找)、STL函数库的应用第五弹——二分函数
分治算法:二分查找!昨天刚说不写算法了,但是突然想起来没写过分治算法的博客,所以强迫症的我…… STL函数库第五弹——二分函数lower_bound().upper_bound().binary_se ...
- Python 常用的操作文件代码
1:统计list中相同的个数,并按大小排序. original_list = ['a', 'b', 'b', 'a', 'd', 'd', 'b', 'z', 'c', 'b', 'r', 's', ...
- 创建SpringMVC项目
学习SpringMVC框架第一步,先创建一个简单项目,了解流程.使用的是Eclipse+Tomcat9.0 创建项目springmvc 新建Dynamic Web Project File->N ...
- 痞子衡嵌入式:解锁i.MXRTxxx上FlexSPI模块自带的地址重映射(Remap)功能
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家介绍的是i.MXRT三位数系列隐藏的FlexSPI Remap功能. 前段时间痞子衡写了一篇文章 <利用i.MXRT1060,1010上新 ...
- TCL(事务控制语言)
#TCL/*Transaction Control Language 事务控制语言 事务:一个或一组sql语句组成一个执行单元,这个执行单元要么全部执行,要么全部不执行. 案例:转账 张三丰 1000 ...
- js 常用业务工具方法 (es5,es6)持续更新
数组去重 数组去重最原始的方法就是使用双层循环. es5: // 使用indexOf function unique(array) { var res = []; for (var i = 0, le ...
- 3分钟教会你如何发布Qt程序
导读:Qt程序编写好以后该如何发布.本文教你使用Qt自带工具windeployqt来进行操作. 本文字数:500,阅读时长大约:3分钟 (1)编写一个简单的程序 我们先做一个简单的窗口,添加一个图片资 ...
- 高并发&性能优化(二)------系统监控工具使用
上一篇主要从总体介绍了高并发&性能优化的相关思路和方法,本篇主要介绍系统监控工具. [CPU查看工具] ------top命令(性能) 进入top命令后,按1即可看到每核CPU的运行指标与详细 ...
- python数据类型和运算符
一.python类型判断 type,isinstance type(变量或常量):返回数据类型 a = 23.3print(type(a))b = 2e3print(b, type(b))输出: &l ...