WebSocket 为浏览器和服务器端提供了双工异步通信的功能,即浏览器可以向服务器发送消息,服务器也可以向浏览器发送消息。WebSocket 需要浏览器的支持,如IE 10+、Chrome 13+、Firefox 6+。
Websocket 是通过一个socket来实现双工异步通讯的能力。但是直接使用WebSocket协议开发程序显得特别烦琐,我门会使用它的子协议STOMP,它是一个更高级级别的协议,STOMP协议使用一个基于帧(frame)的格式来定义信息,与HTTP的request 和response 类似(具有类似于 @RequestMapping 的 @MessageMapping )在后面的内容中可以观察STOMP的frame
广播式
即服务器段友消息时,会将消息发送给所有链接了当前endpoint 的浏览器。
也就是打开多个浏览器tab。链接上websocket 以后一个tab发送信息,其他链接的tab 也能收到。
目录结构:
实现 后台
1. 新建maven项目
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.us.example</groupId>
<artifactId>springWebSocket</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
</parent>
<properties>
<start-class>com.us.WebApplication</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<!-- 核心模块,包括自动配置支持、日志和YAML -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 测试模块,包括JUnit、Hamcrest、Mockito -->
<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-thymeleaf</artifactId>
</dependency>
<!-- 引入Web模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringWebSocket依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
</project>
2.新建WebSocket 的配置类
WebSocketConfig.java
package com.us.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
/**
* Created by yangyibo on 16/12/29.
*/
@Configuration
@EnableWebSocketMessageBroker
//通过EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(message broker)的消息,此时浏览器支持使用@MessageMapping 就像支持@RequestMapping一样。
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.addEndpoint("/endpointWisely").withSockJS();//注册一个Stomp 协议的endpoint,并指定 SockJS协议。
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(message broker)
registry.enableSimpleBroker("/topic"); //广播式应配置一个/topic 消息代理
}
}
3.浏览器向服务器发送的消息接收类
package com.us.example.bean;
/**
* Created by yangyibo on 16/12/29.
* 浏览器向服务器发送的消息使用此类接受
*/
public class Message {
private String name;
public String getName(){
return name;
}
}
4.服务器向浏览器发送的此类消息。
package com.us.example.bean;
/**
* Created by yangyibo on 16/12/29.
* 服务器向浏览器发送的此类消息。
*/
public class Response {
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
private String responseMessage;
public Response(String responseMessage){
this.responseMessage = responseMessage;
}
public String getResponseMessage(){
return responseMessage;
}
}
5.演示控制器代码
package com.us.example.controller;
import com.us.example.bean.Message;
import com.us.example.bean.Response;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
/**
* Created by yangyibo on 16/12/29.
*
*/
@Controller
public class WebSocketController {
@MessageMapping("/welcome")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
@SendTo("/topic/getResponse")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。
public Response say(Message message) throws Exception {
Thread.sleep(1000);
return new Response("Welcome, " + message.getName() + "!");
}
}
实现前台
6. 添加脚本
添加脚本,将stomp.js、sockjs.min.js 以及jQuery 脚本放在src/main/resources/static下。
7.演示页面
在src/main/resources/templates 下新建 ws.html。(源代码会在文章底部给出)
<!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" disabled="disabled" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的名字</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">发送</button>
<p id="response"></p>
</div>
</div>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
}
function connect() {
var socket = new SockJS('/endpointWisely'); //链接SockJS 的endpoint 名称为"/endpointWisely"
stompClient = Stomp.over(socket);//使用stomp子协议的WebSocket 客户端
stompClient.connect({}, function(frame) {//链接Web Socket的服务端。
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/getResponse', function(respnose){ //订阅/topic/getResponse 目标发送的消息。这个是在控制器的@SendTo中定义的。
showResponse(JSON.parse(respnose.body).responseMessage);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = $('#name').val();
//通过stompClient.send 向/welcome 目标 发送消息,这个是在控制器的@messageMapping 中定义的。
stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));
}
function showResponse(message) {
var response = $("#response");
response.html(message);
}
</script>
</body>
</html>
8.配置view Controller
为ws提供便捷的路径映射
package com.us.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
//为ws.HTML 提供便捷的路径映射。
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws").setViewName("/ws");
}
}
9.启动入口
package com.us.example;
/**
* Created by yangyibo on 16/12/29.
*/
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import static org.springframework.boot.SpringApplication.run;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = run(Application.class, args);
}
}
启动后访问 //http://localhost:8080/ws
进行操作
本文参考:《JavaEE开发的颠覆者:Spring Boot实战 》