• 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><groupId>com.baosight</groupId><artifactId>websocket</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.2.RELEASE</version><relativePath/></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency></dependencies></project>
  • WebSocketConfig 配置
package com.baosight.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 {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}
  • MyController 页面请求
package com.baosight.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.baosight.service.WebSocketServer;import java.io.IOException;@Controller
public class MyController {/***  页面请求连接服务器*/@GetMapping("/socket/{cid}")public ModelAndView socket(@PathVariable String cid) {ModelAndView mav=new ModelAndView("/socket");mav.addObject("cid", cid);return mav;}/*** 推送数据接口:到指定客户端*/@ResponseBody@RequestMapping("/socket/push/{cid}")public String pushToWeb(@PathVariable String cid, String message) {try {WebSocketServer.sendInfo(message,cid);} catch (IOException e) {e.printStackTrace();return "推送失败";}return "发送成功";}/*** 推送数据接口:到所有客户端*/@ResponseBody@RequestMapping("/socket/pushAll")public String pushToAllWeb(String message) {try {WebSocketServer.sendInfoToAllClient(message);} catch (IOException e) {e.printStackTrace();return "推送失败";}return "发送成功";}}
  • WebSocketServer 接口实现
package com.baosight.service;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {static Log log= LogFactory.getLog(WebSocketServer.class);//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。private static CopyOnWriteArraySet<WebSocketServer> webSocketSet= new CopyOnWriteArraySet<WebSocketServer>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;//接收sidprivate String sid="";/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session,@PathParam("sid") String sid) {this.session = session;webSocketSet.add(this);     //加入set中addOnlineCount();           //在线数加1log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());this.sid=sid;try {sendMessage("连接成功");} catch (IOException e) {log.error("websocket IO异常");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {webSocketSet.remove(this);  //从set中删除subOnlineCount();           //在线数减1log.info("有一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法* @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {log.info("收到来自窗口"+sid+"的信息:"+message);//群发消息for (WebSocketServer item : webSocketSet) {try {item.sendMessage(message);} catch (IOException e) {e.printStackTrace();}}}@OnErrorpublic void onError(Session session, Throwable error) {log.error("发生错误");error.printStackTrace();}//实现服务器主动推送public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}//群发自定义消息public static void sendInfo(String message,@PathParam("sid") String sid)throws IOException {log.info("推送消息到窗口"+sid+",推送内容:"+message);for (WebSocketServer item : webSocketSet) {try {//这里可以设定只推送给这个sid的,为null则全部推送if(sid==null) {item.sendMessage(message);}else if(item.sid.equals(sid)){item.sendMessage(message);}} catch (IOException e) {continue;}}}//群发自定义消息public static void sendInfoToAllClient(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--;}
}
  • SpringBootApp 启动类
package com.baosight;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringBootApp {public static void main(String[] args) {SpringApplication.run(SpringBootApp.class);}
}
  • application.properties 启动端口配置
server.port=8081
  • websocket.html 测试网页
<html>
<head><meta name="viewport" content="initial-scale=1.0, user-scalable=no" /><script type="text/javascript">var socket;if (typeof (WebSocket) == "undefined") {console.log("您的浏览器不支持WebSocket");} else {console.log("您的浏览器支持WebSocket");//实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接  socket = new WebSocket("ws://localhost:8081/websocket/1");//打开事件  socket.onopen = function () {console.log("Socket 已打开");socket.send("这是来自客户端的消息" + location.href + new Date());};//获得消息事件  socket.onmessage = function (msg) {console.log(msg.data);};//关闭事件  socket.onclose = function () {console.log("Socket已关闭");};//发生了错误事件  socket.onerror = function () {alert("Socket发生了错误");}}</script>
</head>
</html>

SpringBoot集成WebSocket案例:服务端与客户端消息互通相关推荐

  1. 使用WebSocket实现服务端和客户端的通信

    开发中经常会有这样的使用场景.如某个用户在一个数据上做了xx操作, 与该数据相关的用户在线上的话,需要实时接收到一条信息. 这种可以使用WebSocket来实现. 另外,对于消息,可以定义一个类进行固 ...

  2. 使用HTML5的WebSocket实现服务端和客户端数据通信(有演示和源码)

    WebSocket协议是基于TCP的一种新的网络协议.WebSocket是HTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术.依靠这种技术可以实现客户端和服务器端的长连接,双向实时通信. ...

  3. springboot+websocket实现服务端、客户端

    一.引言 小编最近一直在使用springboot框架开发项目,毕竟现在很多公司都在采用此框架,之后小编也会陆续写关于springboot开发常用功能的文章. 什么场景下会要使用到websocket的呢 ...

  4. SpringBoot(23) 集成socket.io服务端和客户端实现通信

    一.前言 websocket和socket.io区别? websocket 一种让客户端和服务器之间能进行双向实时通信的技术 使用时,虽然主流浏览器都已经支持,但仍然可能有不兼容的情况 适合用于cli ...

  5. appollo消息服务器,Springboot 集成 MQTT —— web 服务端实现(apollo 客户端)-Go语言中文社区...

    基于 MQTT 可以实现很多场景,例如现在使用比较多的物联网,还有消息的实时推送.联网的设备连接上 apollo 服务器以后,一直监听 apollo 推送过来的信令/消息即可. 1.web 服务端向联 ...

  6. ssm配置socket_ssm框架中集成websocket实现服务端主动向客户端发送消息

    找了很多配置文档及实例说明,也还是没能成功,最终在csdn博客中发现了基于stomp的消息推送的文章, 下面整理自csdn博客,https://blog.csdn.net/u013627689/art ...

  7. java 集成 cas系统 服务端和客户端配置

    http://blog.csdn.net/yunye114105/article/details/7997041 参考: http://blog.csdn.net/diyagea/article/de ...

  8. socket.io服务端是java_SpringBoot(23) 集成socket.io服务端和客户端实现通信

    @Slf4j @Service(value = "socketIOService") public class SocketIOServiceImpl implements ISo ...

  9. java BIO tcp服务端向客户端消息群发代码教程实战

    前言 项目需要和第三方厂商的服务需要用TCP协议通讯,考虑到彼此双方可能都会有断网重连.宕机重启的情况,需要保证 发生上述情况后,服务之间能够自动实现重新通信.研究测试之后整理如下代码实现.因为发现客 ...

最新文章

  1. python计算四元素组合算法_python – 算法,列表元素之间的最近点
  2. 我也聊聊串口通信协议:用户层通信协议的编制
  3. png 转数组 工具_推荐8款实用在线制图工具
  4. hdu1808-Halloween treats(抽屉原理)
  5. SurfaceFlinger 和 Hardware Composer
  6. Python 的 Magic Methods 指南(转)
  7. (建议收藏)前端面试必问的十六条HTTP网络知识体系
  8. 信息奥赛一本通(1099:第n小的质数)
  9. 【英语学习】【科学】【Glencoe Science】【C】Animal Diversity 目录及术语表
  10. 如何应对倒戈的员工?
  11. 微信小程序教程笔记2
  12. java url 请求 最大长度限制_Http请求 url 请求头 请求体 大小长度限制
  13. MXY-API管理系统安装教程
  14. 网易云音乐评论功能实现(数据库设计)
  15. 第六届“强网杯”全国网络安全挑战赛-青少年专项赛
  16. java应用程序 从 mian函数进入子程序*
  17. 三国志战略版:Daniel_平民掐大佬之《兵法九章》
  18. FileReader 对象实现图片预览
  19. Aspose.Words.FileCorruptedException: The document appears to be corrupted and cannot be loaded
  20. 应用测试一(烤地瓜)——> 隐藏数据

热门文章

  1. influxDB框架 数据存储 TSM 数据操作等详解
  2. 贵州:2018经济增速继续领先 2019“九字真言”主攻高质量
  3. 怎么把网页源码家入hexo博客_从零开始搭建个人博客(超详细)
  4. linux系统里route -n不起作用,Linux系统中的route解析
  5. windows运行linux系统,coLinux:在Windows运行Linux系统(教程)
  6. thinkphp5连接数据库mysql_ThinkPHP学习(三)配置PHP5支持MySQL,连接MySQL数据库
  7. java 对称加密 教程_Java 对称加密算法DES 的使用教程
  8. epub 阅读器_全球与中国EPUB阅读器市场深度调研分析报告
  9. 日报管理系统_好车日报:通用电动车无线电池管理系统;8月皮卡增长39.8%
  10. android expandablelistview横向,Android ExpandableListView使用小结(二)