项目结构:
1).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.hsp</groupId>
<artifactId>SpringBootWebSocket</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootWebSocket</name>
<url>http://maven.apache.org</url>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1-b07</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>SpringBootWebSocket</finalName>
</build>
</project>
2).Message.java
package com.chat;
public class Message {
private String content;
public Message() {
}
public Message(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3).ChattingController.java
package com.chat;
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.RequestParam;
@Controller
public class ChattingController {
// /chatting的处理函数
@MessageMapping("/chatting")
//将结果发送到/chat/message
@SendTo("/chat/message")
//这里传进的参数是Message对象,对应的键是content,
//所以后台的Message对象一定要有content属性
public Message chatting(Message message) throws Exception {
//停1秒,让后台有时间去处理消息
Thread.sleep(1000);
//返回Message的json形式
return new Message(message.getContent());
}
}
4).WebSocketConfig.java
package com.chat;
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;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//namespace 返回数据时加/chat
config.enableSimpleBroker("/chat");
//namespace 经过controller的方法的路径都要加/app
config.setApplicationDestinationPrefixes("/app");
}
//注册websocket
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
}
5).index.html
<!DOCTYPE html>
<html>
<head>
<title>Chatting room</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>
<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">加入聊天室</label>
<button id="connect" class="btn btn-default" type="submit">加入</button>
<button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">退出
</button>
</div>
</form>
</div>
<div class="col-md-6">
<form class="form-inline">
<div class="form-group">
<label for="content">发信息</label>
<input type="text" id="content" class="form-control" placeholder="message...">
</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>聊天记录</th>
</tr>
</thead>
<tbody id="messages">
</tbody>
</table>
</div>
</div>
</form>
</div>
</body>
</html>
6).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;
}
7).app.js
var stompClient = null;
//控制连接函数
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#messages").html("");
}
//如果连接就创建stompClient
function connect() {
//创建一个SockJS
var socket = new SockJS('/websocket');
//使用Stomp协议
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
//接收controller传回来的数据并解析
stompClient.subscribe('/chat/message', function (chatting) {
//chatting是controller对应的处理函数的方法
//content是后台传回来的Message对象的属性
showMessage(JSON.parse(chatting.body).content);
});
});
}
//不连接就销毁stompClient
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
//发送信息
function sendMessage() {
//键一定要content!必须和后台接收对象的属性一致
stompClient.send("/app/chatting", {}, JSON.stringify({'content': $("#content").val()}));
}
//显示消息
function showMessage(message) {
$("#messages").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() { sendMessage(); });
});
8).Application.java
package com.chat;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
9).测试,在浏览器输入:http://localhost:8080/
代码是参考spring官网的资料:https://spring.io/guides/gs/messaging-stomp-websocket/