一、websocket
WebSocket为浏览器和服务端提供了双工异步通信的功能,即浏览器可以向服务端发送消息,服务端也可以向浏览器发送消息。WebSocket葙浏览器的支持,如IE 10+、Chrome 13+,Firefox6+,这对我们现在的浏览器来说都不是问题。
WebSocket是通过一个socket来实现双工异步通信能力的。但是直接使用WebSocket (或 者SockJS,WebSocket协议的模拟,增加了当浏览器不支持WebSocket的时候的兼容支持)协议开发程序显得特别烦琐,我们会使用它的子协议STOMP,它是一个更高级别的协议,STOMP协议使用一个基于帧(frame)的格式来定义消息,与HTTP的request和response类似(具有 类似于@RequestMapping 的@MessageMapping)。
二、广播
在pom.xml 文件中添加websocket依赖的包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置WebSocket,需要在配置类上使用@EnableWebSocketMessageBroker
开启WebSocket,并继承AbstractWebSocketMessageBrokerConfigurer
类。通过@EnableWebSocketMessageBroker
注解开启使用@STOMP协议来传输基于代理的消息,这是控制器支持使用@MessageMapping。"/endpointWisely"
注册STOMP协议的节点,并指定映射的URL和指定使用SockJS协议。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry arg0) {
arg0.addEndpoint("/endpointWisely").withSockJS();
}
}
Controller层
当浏览器向服务器发送请求时,通过@MessageMapping
映射/welcome这个地址,相当于@RequestMapping
。SendTo
当服务器有消息时,会对这个路径的浏览器发送消息。
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WsController {
@MessageMapping("welcome")
@SendTo("/demo_2/topic/getResponse")
public String say(String message) throws Exception {
return message;
}
}
websocketBroadcast.html,这里需要在static文件中添加sockjs.min.js
和stomp.min.js
和jquery-2.1.1.min.js
,这个可以去网上自行下载。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Spring Boot WebSocket+广播式</title>
</head>
<body onload="disconnect()">
<noscript>
<h2 style="color:#ff0000">貌似你的浏览器不支持websocket</h2>
</noscript>
<div>
<div>
<button id="connect" onclick="connect()">连接</button>
<button id="disconnect" onclick="disconnect();">断