您的当前位置:首页详解springboot集成websocket的两种实现方式

详解springboot集成websocket的两种实现方式

2024-03-30 来源:乌哈旅游
详解springboot集成websocket的两种实现⽅式

WebSocket跟常规的http协议的区别和优缺点这⾥⼤概描述⼀下

⼀、websocket与http

http协议是⽤在应⽤层的协议,他是基于tcp协议的,http协议建⽴链接也必须要有三次握⼿才能发送信息。http链接分为短链接,长链接,短链接是每次请求都要三次握⼿才能发送⾃⼰的信息。即每⼀个request对应⼀个response。长链接是在⼀定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。 WebSocket是HTML5中的协议, 他是为了解决客户端发起多个http请求到服务器资源浏览器必须要经过长时间的轮训问题⽽⽣的,他实现了多路复⽤,他是全双⼯通信。在webSocket协议下客服端和浏览器可以同时发送信息。

⼆、HTTP的长连接与websocket的持久连接

HTTP1.1的连接默认使⽤长连接(persistent connection),

即在⼀定的期限内保持链接,客户端会需要在短时间内向服务端请求⼤量的资源,保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。

在⼀个TCP连接上可以传输多个Request/Response消息对,所以本质上还是Request/Response消息对,仍然会造成资源的浪费、实时性不强等问题。

如果不是持续连接,即短连接,那么每个资源都要建⽴⼀个新的连接,HTTP底层使⽤的是TCP,那么每次都要使⽤三次握⼿建⽴TCP连接,即每⼀个request对应⼀个response,将造成极⼤的资源浪费。

长轮询,即客户端发送⼀个超时时间很长的Request,服务器hold住这个连接,在有新数据到达时返回Response

websocket的持久连接 只需建⽴⼀次Request/Response消息对,之后都是TCP连接,避免了需要多次建⽴Request/Response消息对⽽产⽣的冗余头部信息。

Websocket只需要⼀次HTTP握⼿,所以说整个通讯过程是建⽴在⼀次连接/状态中,⽽且websocket可以实现服务端主动联系客户端,这是http做不到的。

springboot集成websocket的不同实现⽅式:pom添加依赖

org.springframework.boot

spring-boot-starter-websocket

因涉及到js连接服务端,所以也写了对应的html,这⾥集成下thymeleaf模板,前后分离的项⽬这⼀块全都是前端做的

org.springframework.boot

spring-boot-starter-thymeleaf

配置⽂件:

server: port: 8885

#添加Thymeleaf配置thymeleaf: cache: false

prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8

content-type: text/html

1:⾃定义WebSocketServer,使⽤底层的websocket⽅法,提供对应的onOpen、onClose、onMessage、onError⽅法1.1:添加webSocketConfig配置类

/**

* 开启WebSocket⽀持

* Created by huiyunfei on 2019/5/31. */

@Configuration

public class WebSocketConfig { @Bean

public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}

1.2:添加webSocketServer服务端类

package com.example.admin.web; /**

* Created by huiyunfei on 2019/5/31. */

@ServerEndpoint(\"/websocket/{sid}\")@Component@Slf4j

public class WebSocketServer {

//静态变量,⽤来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0;

//concurrent包的线程安全Set,⽤来存放每个客户端对应的MyWebSocket对象。

private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet();

//与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session;

//接收sid

private String sid=\"\"; *//**

* 连接建⽴成功调⽤的⽅法*//* @OnOpen

public void onOpen(Session session, @PathParam(\"sid\") String sid) { this.session = session;

webSocketSet.add(this); //加⼊set中 addOnlineCount(); //在线数加1

log.info(\"有新窗⼝开始监听:\"+sid+\当前在线⼈数为\" + getOnlineCount()); this.sid=sid; try {

sendMessage(\"连接成功\"); } catch (IOException e) {

log.error(\"websocket IO异常\"); } } *//**

* 连接关闭调⽤的⽅法 *//*

@OnClose

public void onClose() {

webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1

log.info(\"有⼀连接关闭!当前在线⼈数为\" + getOnlineCount()); } *//**

* 收到客户端消息后调⽤的⽅法 *

* @param message 客户端发送过来的消息*//* @OnMessage

public void onMessage(String message, Session session) { log.info(\"收到来⾃窗⼝\"+sid+\"的信息:\"+message); //群发消息

for (WebSocketServer item : webSocketSet) { try {

item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } *//** *

* @param session * @param error *//*

@OnError

public 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 synchronized int getOnlineCount() { return onlineCount; }

public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; }

public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; }

public static CopyOnWriteArraySet getWebSocketSet() { return webSocketSet; }}

1.3:添加对应的controller

@Controller

@RequestMapping(\"/system\")public class SystemController { //页⾯请求

@GetMapping(\"/index/{userId}\")

public ModelAndView socket(@PathVariable String userId) { ModelAndView mav=new ModelAndView(\"/socket1\"); mav.addObject(\"userId\ return mav; }

//推送数据接⼝ @ResponseBody

@RequestMapping(\"/socket/push/{cid}\")

public Map pushToWeb(@PathVariable String cid, String message) { Map result = new HashMap(); try {

WebSocketServer.sendInfo(message,cid); result.put(\"code\

result.put(\"msg\ } catch (IOException e) { e.printStackTrace(); }

return result; }

1.4:提供socket1.html页⾯

Titlehello world!

总结:

浏览器debug访问 localhost:8885/system/index/1跳转到socket1.html,js⾃动连接server并传递cid到服务端,服务端对应的推送消息到客户端页⾯(cid区分不同的请求,server⾥提供的有群发消息⽅法)2.1:基于STOMP协议的WebSocket

使⽤STOMP的好处在于,它完全就是⼀种消息队列模式,你可以使⽤⽣产者与消费者的思想来认识它,发送消息的是⽣产者,接收消息的是消费者。⽽消费者可以通过订阅不同的destination,来获得不同的推送消息,不需要开发⼈员去管理这些订阅与推送⽬的地之前的关系,spring官⽹就有⼀个简单的spring-boot的stomp-demo,如果是基于springboot,⼤家可以根据spring上⾯的教程试着去写⼀个简单的demo。

提供websocketConfig配置类

/**

* @Description:

registerStompEndpoints(StompEndpointRegistry registry)configureMessageBroker(MessageBrokerRegistry config)

这个⽅法的作⽤是定义消息代理,通俗⼀点讲就是设置消息连接请求的各种规范信息。

registry.enableSimpleBroker(\"/topic\")表⽰客户端订阅地址的前缀信息,也就是客户端接收服务端消息的地址的前缀信息(⽐较绕,看完整个例⼦,⼤概就能明⽩了)registry.setApplicationDestinationPrefixes(\"/app\")指服务端接收地址的前缀,意思就是说客户端给服务端发消息的地址的前缀 * @Author:hui.yunfei@qq.com * @Date: 2019/5/31 */

@Configuration

@EnableWebSocketMessageBroker

public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

// 这个⽅法的作⽤是添加⼀个服务端点,来接收客户端的连接。

// registry.addEndpoint(\"/socket\")表⽰添加了⼀个/socket端点,客户端就可以通过这个端点来进⾏连接。// withSockJS()的作⽤是开启SockJS⽀持, @Override

public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(\"/socket\").withSockJS(); }

@Override

public void configureMessageBroker(MessageBrokerRegistry registry) {

//表⽰客户端订阅地址的前缀信息,也就是客户端接收服务端消息的地址的前缀信息 registry.enableSimpleBroker(\"/topic\");

//指服务端接收地址的前缀,意思就是说客户端给服务端发消息的地址的前缀 registry.setApplicationDestinationPrefixes(\"/app\"); }}

2.2:controller提供对应请求的接⼝

//页⾯请求

@GetMapping(\"/socket2\")

public ModelAndView socket2() {//@PathVariable String userId ModelAndView mav=new ModelAndView(\"html/socket2\"); //mav.addObject(\"userId\ return mav; } /**

* @Description:这个⽅法是接收客户端发送功公告的WebSocket请求,使⽤的是@MessageMapping * @Author:hui.yunfei@qq.com * @Date: 2019/5/31 */

@MessageMapping(\"/change-notice\")//客户端访问服务端的时候config中配置的服务端接收前缀也要加上 例:/app/change-notice @SendTo(\"/topic/notice\")//config中配置的订阅前缀记得要加上 public CustomMessage greeting(CustomMessage message){ System.out.println(\"服务端接收到消息:\"+message.toString()); //我们使⽤这个⽅法进⾏消息的转发发送!

//this.simpMessagingTemplate.convertAndSend(\"/topic/notice\可以使⽤定时器定时发送消息到客户端) // @Scheduled(fixedDelay = 1000L) // public void time() {

// messagingTemplate.convertAndSend(\"/system/time\ // }

//也可以使⽤sendTo发送 return message; }

2.3:提供socket2.html

Spring Boot+WebSocket+⼴播式

貌似你的浏览器不⽀持websocket

2.4:对应的js引⽤可以去⽹上下载

2.5:浏览器debug访问localhost:8885/system/socket2,点击连接连接到服务器,数据内容可以推送到服务器以及服务器消息回推。2.6:实现前端和服务端的轮训可以页⾯Ajax轮训也可以后端添加定时器

@Component

@EnableSchedulingpublic class TimeTask {

private static Logger logger = LoggerFactory.getLogger(TimeTask.class);

@Scheduled(cron = \"0/20 * * * * ?\") public void test(){

System.err.println(\"********* 定时任务执⾏ **************\"); CopyOnWriteArraySet webSocketSet = WebSocketServer.getWebSocketSet(); int i = 0 ;

webSocketSet.forEach(c->{ try {

c.sendMessage(\" 定时发送 \" + new Date().toLocaleString()); } catch (IOException e) { e.printStackTrace(); } });

System.err.println(\"/n 定时任务完成.......\"); }}

基于STOMP协议的⼴播模式和点对点模式消息推送可参考:

到此这篇关于springboot集成websocket的两种实现⽅式的⽂章就介绍到这了,更多相关springboot集成websocket内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

因篇幅问题不能全部显示,请点此查看更多更全内容