关注 “弋凡”(YiFan)微信公众号吧 记录简单笔记 做你的最爱

websocket 是什么?

是一种网络通信协议,很多高级功能都需要它

为什么要使用websocket?

已经有了HTTP协议 为撒还需要使用WebSocket 嘞?

HTTP 是客户端请求服务端响应数据,但是我们如果想服务端给客户端发送消息嘞?

于是乎就有了这种协议,客户端,服务端可以双向发送消息

最典型的就是聊天系统

stomp

stomp 既 Simple (or Streaming) Text Orientated Messaging Protocol

简单(流)文本定向消息协议

为什么需要stomp?

常规的websocket连接和普通的TCP基本上没区别

所以STOMP在websocket上提供了一中基于帧线路格式(frame-based wire format)

简单一点,就是在我们的websocket(TCP)上面加了一层协议,使双方遵循这种协议来发送消息

服务端:/app,这里访问服务端,前缀通过设定的方式访问

用户:/user,这里针对的是用户消息的传递,针对于当前用户进行传递。

其他消息:/topic、/queue,这两种方式。都是定义出来用于订阅服务端

SpringBoot WebSocket 案例

导入pom依赖

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

websocket配置 - WebSocketConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {// 基于STOMP协议的WebSocket@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {// 注册一个websocket端点,客户端将使用它连接到我们的websocket服务器。registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();}// 注册相关服务@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {//定义了服务端接收地址的前缀,也即客户端给服务端发消息的地址前缀registry.setApplicationDestinationPrefixes("/yifan");//定义了一个(或多个)客户端订阅地址的前缀信息,也就是客户端接收服务端发送消息的前缀信息registry.enableSimpleBroker("/topic","/user");// 点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/registry.setUserDestinationPrefix("/user/");}
}

服务端 controller

@Controller
@RequestMapping("yifan")
public class ChatController {@Autowiredprivate SocketService socketService;/* 接收消息     @SendToUser 谁发送的返回给谁  */@MessageMapping("/chat")public void broadCast(SocketMessage message){socketService.sendToMsg(message);}/* 发送给个人*/@MessageMapping("/chatTo")public void serverSendUesrMsg(SocketMessage message){socketService.sendToUserMsg(message);}
}

客户端 网页

需要准备

  • jquery.min.js https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js
  • sockjs.min.js sockjs
  • stomp.js stomp
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" name="viewport"><title>YF 频道</title><link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"><link rel="stylesheet" href="/css/mycss.css">
</head>
<body><div style="background: #6777ef;width: 100vw ;height: 100px;text-align: center;  margin-bottom: 50px;"><p style="font-weight: bold;color: white;font-size: 24px;  padding-top: 15px  ">YFTOOLS</p><input type="hidden" th:value="${session.user.uname}" class="uname"><div class="container tools-top-page">弋凡 聊天频道 </div>
</div><div class="container" id="app"><div class="row" style="border: 1px solid #000000"><div class="col col-sm-8" id="msg" style="border-right: 2px solid #6777ef;height: 500px;overflow:auto; " ></div><div class="col col-sm-4"><ul id="ras"><li  v-for="(item,i) in users"><input type="radio" :value="item.uname" name="redio"> {{item.uname}}</li></ul></div></div><div class="row"><div class="col-8"><textarea class="form-control" id="texts"style="position: absolute;left: 0px"></textarea></div><div class="col-4"><button class="btn btn-info one">个人</button><button class="btn btn-info all">群发</button></div></div>
</div>
</body><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="/js/chat/sockjs.min.js"></script>
<script src="/js/chat/stomp.js"></script>
<script src="/js/vue.min.js"></script>
<script src="/js/axios.min.js"></script>
<script>new Vue({el:'#app',data:{users:[],},mounted(){this.chat();},methods:{chat(){axios.get('/user/All').then(res=>{this.users = res.data;})}}});var name ='';// 连接var socket = new SockJS("http://126.75.109.85:81/socket");stompClient = Stomp.over(socket);stompClient.connect( {}, function (frame) {//订阅广播stompClient.subscribe('/topic/message', function (res) {$("#msg").append("<p class='text-center' ><span>"+JSON.parse(res.body).name +"</span>" + "<span style='color: red'> (全体消息) : </span>" +  JSON.parse(res.body).message  +  " </p>");});// 个人  == > 接收的消息 (订阅自己)name = $(".uname").val();stompClient.subscribe('/user/'+name+'/ptp', function (res) {console.log(name+"---------");// showGreeting(JSON.parse(data.body).content);console.log("res => "+res);$("#msg").append("  <div class='media text-left'> <img src='https://q4.qlogo.cn/g?b=qq&amp;nk=2050781802@qq.com&amp;s=3?d=retro' alt='null'  class='rounded-circle mr-1' width='40px'>" +" <div class='media-body'><h5 class='mt-0'> "+JSON.parse(res.body).name+" </h5>"+JSON.parse(res.body).message +"</div>  </div>  ");});},function (error) {console.log('连接失败【' + error + '】');});// 断开连接$("#disconnect").click(function () {if (stompClient !== null) {stompClient.disconnect();alert('用户: '+name+'   ...断开连接...');$("#msg").html("");}});// 单个发送$(".one").click(function () {var info = {};info.toname = $('input:radio:checked').val();info.name = name ;info.message = $("#texts").val();info.date = "1212";if(info.toname != info.name && info.message != null && info.message!='' ){$("#msg").append("  <div class='media text-right'>" +" <div class='media-body'><h5 class='mt-0'> "+ info.name+" </h5>"+info.message +"</div>  <img class='rounded-circle mr-1' width='40px' src='https://q4.qlogo.cn/g?b=qq&amp;nk=2050781802@qq.com&amp;s=3?d=retro' alt='null'> </div>  ");stompClient.send("/yifan/chatTo", {}, JSON.stringify(info) );}else {alert("不能给自己发送消息,内容不能为空~")}clearText();});// 群发$(".all").click(function () {var info = {};info.name = name;info.message = $("#texts").val();info.date = "1212";stompClient.send("/yifan/chat", {}, JSON.stringify(info) );clearText();});// 清空输入框function clearText(){$("#texts").val("");}//窗口关闭时,关闭连接window.οnbefοreunlοad=function() {socket.close();};</script>
</html>

效果图


end –

快来关注“弋凡”微信公众号吧

SpringBoot WebSocket Stomp相关推荐

  1. Springboot+Websocket+Stomp实现PC兼容,及微信小程序连接

    导入maven依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId> ...

  2. springboot+websocket+stomp.js

    前端通过websocket订阅后台实时发送消息 1.引入stomp.min.js,源码地址:https://www.bootcdn.cn/stomp.js/ // Generated by Coffe ...

  3. WebSocket Stomp 通讯

    NIO 通讯 netty 实现的socket 通讯 应用netty 实现异步通信.实现消息推送和反馈,广播的功能 netty:port: 8888 #监听端口bossThread: 2 #线程数wor ...

  4. 【Java分享客栈】SpringBoot整合WebSocket+Stomp搭建群聊项目

    前言 前两周经常有大学生小伙伴私信给我,问我可否有偿提供毕设帮助,我说暂时没有这个打算,因为工作实在太忙,现阶段无法投入到这样的领域内,其中有两个小伙伴又问到我websocket该怎么使用,想给自己的 ...

  5. springboot+websocket构建在线聊天室(群聊+单聊)

    系列导读: 1.springboot+websocket构建在线聊天室(群聊+单聊) 2.Spring Boot WebSocket:单聊(实现思路) 3.Websocket Stomp+Rabbit ...

  6. Spring websocket+Stomp+SockJS 实现实时通信 详解

    Spring websocket+Stomp+SockJS 实时通信详解 一.三者之间的关系 Http连接为一次请求(request)一次响应(response),必须为同步调用方式.WebSocke ...

  7. GPS转换百度地图坐标websocket(stomp)实现动态打点

    序        这会已经下班乐,本来觉得这个好像没有什么新东西.最后决定还是趁现在下班写写是因为要让大家看看单技术组合使用的意义.这里就是在上次springBoot+thymeleaf+layui后 ...

  8. springboot websocket

    大家好,我是烤鸭: 今天想分享一下springboot+websocket. 之前接到一个需求,需要在页面监听后台的数据(输入邮箱后,需要用户打开邮箱,页面监听用户是否点击激活邮件).之前的实现方式, ...

  9. SpringBoot +WebSocket实现简单聊天室功能实例

    SpringBoot +WebSocket实现简单聊天室功能实例) 一.代码来源 二.依赖下载 三.数据库准备(sql) 数据库建表并插入sql 四.resources文件配置 application ...

最新文章

  1. MSF(六):后渗透
  2. tempdb数据库清理_如何检测和防止TempDB数据库意外增长
  3. api hook 例子,截获封包(转载)
  4. python实现强化学习
  5. python中变量名有哪些
  6. pentaho资源库迁移-MySQL
  7. 怎么使用JavaScript进行进制…
  8. unison 安装使用
  9. 安全漏洞防御(8) DDOS 攻击的防范教程
  10. 零基础入门金融风控之贷款违约预测挑战赛-task01
  11. 2017 iOS最新面试题汇总(二)
  12. Win10自带的中文输入法在Sublime Text中不跟随光标的解决方案
  13. 【Linux】嵌入式Linux系统的移植(下篇:BootLoader,以U-Boot为例)
  14. MQ消息队列搭建命令及方法
  15. 互联网架构的演进历程
  16. rstudio安装后打不开_r语言和rstudio的安装
  17. 英语单词: thunk
  18. 女性健康养生资讯网类织梦模板(带手机端)【测试可搭建】
  19. Swiper 中常见的属性以及方法
  20. 第一篇 厚黑学 三、厚黑经

热门文章

  1. 【Cocosd2d实例教程八】Cocos2d实现碰撞检测(含实例)
  2. 剖析Elasticsearch集群系列第一篇 Elasticsearch的存储模型和读写操作
  3. Mesos在传统金融企业的实践——平安科技陈秋浩实录分享
  4. 京东10亿级调用量背后的高可用网关系统架构实践!
  5. hadoop和spark搭建记录
  6. 跨平台传输中使用base64来保证非ascii码字符串的完整性
  7. android studio 与gradle的版本对应
  8. 细思极恐!未来百万人将下岗十大职业将消失
  9. c语言奇数值结点链表,习题11-7 奇数值结点链表 (20 分)
  10. 抢椅子游戏java_游戏教案小班抢椅子