<?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 https://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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>chat01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>chat01</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</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</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
<!-- <version>0.48</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.yl.chat01.domain;
import java.io.Serializable;
import java.util.Date;
public class Chat implements Serializable {
private String from;
private String to;
private String content;
private Date date;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Chat{" +
"from='" + from + '\'' +
", to='" + to + '\'' +
", content='" + content + '\'' +
", date=" + date +
'}';
}
}
package com.yl.chat01.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;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
// 注册端点,用于前端建立连接的
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").setAllowedOrigins("http://localhost:8080").withSockJS();
}
// 配置消息代理,通过广播的形式来传递消息
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic","/queue");
}
}
package com.yl.chat01.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password("{noop}123")
.roles("admin")
.and()
.withUser("root")
.password("{noop}123")
.roles("admin");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().formLogin().permitAll();
}
}
package com.yl.chat01.controller;
import com.yl.chat01.domain.Chat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import java.security.Principal;
import java.util.Date;
@Controller
public class GreetingController {
// /**
// * 群聊
// * @param message
// * @return
// */
// @MessageMapping("/hello") //发送消息请求
// @SendTo("/topic/greetings") //消息广播
// public Message greeting(Message message) {
// return message;
// }
//单聊发送消息模板
@Autowired
SimpMessagingTemplate simpMessagingTemplate;
/**
* 单聊
* @param principal
* @param chat
*/
@MessageMapping("/onlineChat")
public void chat(Principal principal, Chat chat) {
chat.setFrom(principal.getName());
chat.setDate(new Date());
simpMessagingTemplate.convertAndSendToUser(chat.getTo(),"/queue/chat",chat);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<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>
</head>
<body>
<div id="chat"></div>
<div>
<label for="username">请输入目标用户名:</label>
<input type="text" id = "username" placeholder="用户名"/>
<label for="content">请输入聊天内容</label>
<input type="text" id="content" placeholder="聊天内容"/>
</div>
<input type="button" value="发送" id="send"/>
<script>
var stompClient;
$(function () {
connect();
//发送消息到后台
$("#send").click(function () {
stompClient.send("/onlineChat",{},JSON.stringify({'to':$('#username').val(),'content':$("#content").val()}))
})
})
function connect() {
//获取连接地址
var socketjs = new SockJS("/chat");
stompClient = Stomp.over(socketjs);
//建立连接
stompClient.connect({},function (frame) {
//订阅消息
stompClient.subscribe("/user/queue/chat",function (obj) {
var msg = JSON.parse(obj.body);
$("#chat").append("<div>"+ "消息来自于:" +msg.from+ " ,消息内容为:" + msg.content+ " ,发送时间:" + msg.date+"</div>")
})
})
}
</script>
</body>
</html>
6.1 客户端A,用admin登录
6.2 客户端B,用root用户登录
6.3 互相发送消息
客户端A:
客户端B:
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_41359273/article/details/122861707
内容来源于网络,如有侵权,请联系作者删除!