扫码一下
查看教程更方便
在本章中,让我们了解如何使用带有 Web Socket 套接字的 Spring Boot 构建交互式 Web 应用程序。
要使用 Web 套接字在 Spring Boot 中构建交互式 Web 应用程序,您需要添加以下依赖项。
Maven 用户应在 pom.xml 文件中添加以下依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version> </dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.0</version>
</dependency>
Gradle 用户可以在 build.gradle 文件中添加以下依赖项
compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:webjars-locator")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
compile("org.webjars:bootstrap:3.3.7")
compile("org.webjars:jquery:3.1.0")
让我们创建一个消息处理控制器来处理 STOMP 消息传递。 STOMP 消息可以路由到 @Controller
类文件。 例如,GreetingController
被映射为处理发送到目标“/hello”的消息。
package com.jiyik.websocketapp;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
现在,为 STOMP 消息配置 Spring。 编写一个继承 AbstractWebSocketMessageBrokerConfigurer
类的 WebSocketConfig 类文件,如下所示。
package com.jiyik.websocketapp;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/jiyik-websocket").withSockJS();
}
}
@EnableWebSocketMessageBroker
注解用于配置 Web 套接字消息代理以创建 STOMP 端点。
我们可以在 src/main/resources/static/ 下创建一个浏览器客户端文件 index.html,如下所示
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<link href = "/webjars/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<link href = "/main.css" rel = "stylesheet">
<script src = "/webjars/jquery/jquery.min.js"></script>
<script src = "/webjars/sockjs-client/sockjs.min.js"></script>
<script src = "/webjars/stomp-websocket/stomp.min.js"></script>
<script src = "/app.js"></script>
</head>
<body>
<noscript>
<h2 style = "color: #ff0000">
Seems your browser doesn't support Javascript! Websocket relies on Javascript being
enabled. Please enable Javascript and reload this page!
</h2>
</noscript>
<div id = "main-content" class = "container">
<div class = "row">
<div class = "col-md-6">
<form class = "form-inline">
<div class = "form-group">
<label for = "connect">WebSocket connection:</label>
<button id = "connect" class = "btn btn-default" type = "submit">Connect</button>
<button id = "disconnect" class = "btn btn-default" type = "submit" disabled = "disabled">Disconnect
</button>
</div>
</form>
</div>
<div class = "col-md-6">
<form class = "form-inline">
<div class = "form-group">
<label for = "name">What is your name?</label>
<input type = "text" id = "name" class = "form-control" placeholder = "Your name here...">
</div>
<button id = "send" class = "btn btn-default" type = "submit">Send</button>
</form>
</div>
</div>
<div class = "row">
<div class = "col-md-12">
<table id = "conversation" class = "table table-striped">
<thead>
<tr>
<th>Greetings</th>
</tr>
</thead>
<tbody id = "greetings"></tbody>
</table>
</div>
</div>
</div>
</body>
</html>
让我们创建一个 app.js 文件来使用 STOMP 来消费和生成消息。
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
} else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
var socket = new SockJS('/tutorialspoint-websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function (greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
$(function () {
$( "form" ).on('submit', function (e) {e.preventDefault();});
$( "#connect" ).click(function() { connect(); });
$( "#disconnect" ).click(function() { disconnect(); });
$( "#send" ).click(function() { sendName(); });
});
主 Spring Boot 应用程序的代码如下所示。
package com.jiyik.websocketapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebSocketappApplication {
public static void main(String[] args) {
SpringApplication.run(WebSocketappApplication.class, args);
}
}