一、首先pom依赖
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>chat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>chat</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<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-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<!--socket前端库-->
<dependency>
<groupId>org.webjars.npm</groupId>
<artifactId>mdui</artifactId>
<version>0.4.0</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
<version>0.37</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3-1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<!--war包添加外部tomcat依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<!--打包的时候可以不用包进去,别的设施会提供。事实上该依赖理论上可以参与编译,测试,运行等周期。
相当于compile,但是打包阶段做了exclude操作-->
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>chatroom</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、websocket配置类
package com.example.chat.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* @Author: 韩老魔
* ebsocket配置类
* @Date: 2019/4/17 0017 17:02
*/
@Configuration
@EnableWebSocketMessageBroker//使用此注解来标识使能WebSocket的broker.即使用broker来处理消息.
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
/**
* 连接路径配置
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
/*
* 路径"/websocket"被注册为STOMP端点,对外暴露,客户端通过该路径获取与socket的连接
*/
registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
}
/**
* 服务端接收消息路径配置
* @param config
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
//消息代理的前缀 该路径消息会被代理通过广播方式发给客户端(广播路径)
config.enableSimpleBroker("/topic");
/*
* 过滤该路径集合发送过来的消息,被@MessageMapping注解的方法接收处理具体决定广播还是单点发送到客户端
*/
config.setApplicationDestinationPrefixes("/app","/queue");
}
}
三、消息实体类
package com.example.chat.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* @Author: 韩老魔
* 消息类
* @Date: 2019/4/17 0017 19:40
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Message {
private String name; //发送人
private String content; //发送消息
private String date;
}
四、控制器
package com.example.chat.controller;
import com.example.chat.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author: 韩老魔
* @Date: 2019/4/17 0017 19:26
*/
@Controller
public class WebSocketController {
@Autowired
private SimpMessagingTemplate messagingTemplate;
/*页面入口*/
@RequestMapping("/chat")
public String chat() {
return "chat";
}
/**
* 群发
* @param message
* @return
* @throws Exception
*/
@MessageMapping("/hello") //接收/app/hello路径发来的信息:/app被@MessageMapping拦截,/hello被注解内参数拦截
@SendTo("/topic/greetings")//接收上面路径发来的消息后在发送到广播的路径上 即会被代理进行广播群发
public Message messageHandling(Message message) throws Exception {
return message;
}
}
五、设置定时器(写着玩的 可以不要)
package com.example.chat.job;
import com.example.chat.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Author: 韩老魔
* @Date: 2019/4/17 0017 20:27
*/
@Configuration
public class MyJob {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Scheduled(fixedRate = 10000)
public void send() {
SimpleDateFormat sdf=new SimpleDateFormat();
String formatDate = sdf.format(new Date());
messagingTemplate.convertAndSend("/topic/greetings", new Message("定时任务:", "检测通信", formatDate));
}
}
六、yml配置
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
cache: false #关闭缓存
server:
port: 8081
servlet:
context-path: /chatroom
七、前端模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>吐槽</title>
<meta charset="utf-8" name="viewport" content="width=device-width">
<link rel="stylesheet" th:href="@{/webjars/mdui/dist/css/mdui.css}">
<script th:src="@{/webjars/mdui/dist/js/mdui.js}"></script>
<script th:src="@{/webjars/jquery/jquery.min.js}"></script>
<script th:src="@{/webjars/sockjs-client/sockjs.min.js}"></script>
<script th:src="@{/webjars/stomp-websocket/stomp.min.js}"></script>
<!--bug:1.未提取jsp 2.未做非法字符过滤 3.信息满屏未做定时器清屏处理-->
<!--websocket逻辑: 连接 接收 发送 (基于路径,类似RabbitMQ)-->
<!--文字浮动特效 辣鸡-->
<!--<script th:src="@{/jquery.marquee.js}"></script>-->
<!--<script th:src="@{/jquery.pause.js}"></script>-->
<!--<script th:src="@{/jquery.easing.min.js}"></script>-->
</head>
<body class="mdui-theme-primary-indigo mdui-theme-accent-pink" th:style="'background:url(' + '/chatroom/background.png'+ ');'">
<div class="mdui-container">
<span class="mdui-typo-title">kicol的聊天室</span>
<a class="mdui-btn mdui-btn-icon" th:href="@{/}"><i
class="mdui-icon material-icons">exit</i></a>
</div>
</div>
<div>
<label for="name">用户名</label>
<input type="text" id="name" placeholder="用户名">
</div>
<div>
<button id="connect" type="button">连接</button>
<button id="disconnect" type="button" disabled="disabled">断开连接</button>
</div>
<div id="chat" style="display: none;">
<div>
<label for="name">请输入聊天内容</label>
<input type="text" id="content" placeholder="聊天内容">
</div>
<button id="send" type="button">发送</button>
<div id="greetings" class="marquee">
<div id="conversation" style="display: none;">群聊进行中。。。</div>
</div>
</div>
<script th:inline="javascript">
var stompClient = null;
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
$("#chat").show();
} else {
$("#conversation").hide();
$("#chat").hide();
}
$("#greetings").html("");
}
function connect() {
if (!$("#name").val()) {
return;
}
/*1.与服务端连接,客户端通过/chat路径接入WebSocket服务*/
var socket = new SockJS('/chatroom/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
/*2.接收来自服务端的广播消息,通过/topic路径*/
stompClient.subscribe('/topic/greetings', function (greetings) {
showGreeting(JSON.parse(greetings.body));
console.log(greetings);
});
});
}
function disconnect() {
if (stompClient !== null) {
stompClient.disconnect();
}
setConnected(false);
}
/*3.向服务端发送消息*/
function sendname() {
//获取当前时间
var date = new Date().toLocaleString();
// 该web客户端通过/app/hello路径(被@MessageMapping接收)向服务端发送消息(json格式)
stompClient.send("/app/hello", {},
JSON.stringify({'name': $("#name").val(), 'content': $("#content").val(), 'date': date}));
}
function showGreeting(message) {
$("#greetings")
// .append("<div class='marquee'>" + message.name + ":" + message.content + "</div>");
.append("<div class='marquee'>" + message.name + ":" + message.content + "-------time:" +message.date + "</div>");
// //设置该div特效
// $('.marquee').marquee({
// speed: 50,
// gap: 50,
// delayBeforeStart: 0,
// direction: 'left',
// duplicated: true,
// pauseOnHover: true,
// delayBeforeStart:0,
// startVisible:true
// });
}
$(function () {
$("#connect").click(function () {
connect();
});
$("#disconnect").click(function () {
disconnect();
});
$("#send").click(function () {
sendname();
});
});
</script>
</body>
</html>
八、启动后访问 http://localhost:8081/chatroom/chat