開發(fā)環(huán)境
第一步:搭建springboot項目
-
使用 IDEA济蝉,file-->new Object
按找如上步驟然后一直next瓷患,然后finish朴下,springboot項目已經(jīng)建立完成建瘫,是不是很快很簡單榕栏。
目錄結(jié)構(gòu)如下:
第二步:配置websocket
- 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</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>
```
-
建立如下目錄結(jié)構(gòu)
- domain 消息返送和接受的實體類
/**
* 發(fā)生消息實體
*/
public class Sendmessage {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* 響應(yīng)消息實體
*/
public class Receivemessage {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Receivemessage(String content) {
this.content = content;
}
}
- WebSocketConfig.java 配置websocket
/**
* WebSocket 配置
*/
@Configuration
//注解開啟使用STOMP協(xié)議來傳輸基于代理(message broker)的消息,這時控制器支持使用@MessageMapping,就像使用@RequestMapping一樣
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {//注冊STOMP協(xié)議的節(jié)點(endpoint),并映射指定的url
//注冊一個STOMP的endpoint,并指定使用SockJS協(xié)議
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic"); //廣播式應(yīng)配置一個/topic消息代理
registry.setApplicationDestinationPrefixes("/app"); //客戶端訪問前綴
}
}
- 控制層代碼
@Controller
public class WebSocketController {
@MessageMapping("/hello") // 相當(dāng)springMVC 中的RequestMapping
@SendTo("/topic/greetings")
public Receivemessage greeting(Sendmessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Receivemessage("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
前端JS和Html
- 在resources目錄下新建static目錄渴频,spring boot 靜態(tài)文件默認是放在這個目錄下,如果不理解請移步springboot入門竭恬。在static目錄下新建index.html ,app.js ,main.css 三個文件。
index.html 內(nèi)容
<!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
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('/gs-guide-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(); });
});
main.css
body {
background-color: #f5f5f5;
}
#main-content {
max-width: 940px;
padding: 2em 3em;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
到這項目就完成了熬的,我們運行DemoApplication 來看我們的項目
沒問題已經(jīng)可以發(fā)送消息了痊硕,趕緊去試一試吧。