Commit b9e802e4 authored by 杨伊博's avatar 杨伊博

point to point is work

parent 37faeaa7
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
</parent> </parent>
<properties> <properties>
<start-class>com.us.WebApplication</start-class> <start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
</properties> </properties>
...@@ -39,6 +39,7 @@ ...@@ -39,6 +39,7 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<!-- 引入Web模块 --> <!-- 引入Web模块 -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -51,11 +52,12 @@ ...@@ -51,11 +52,12 @@
<artifactId>spring-boot-starter-websocket</artifactId> <artifactId>spring-boot-starter-websocket</artifactId>
</dependency> </dependency>
<!-- 引入security模块 -->
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-messaging</artifactId> <artifactId>spring-boot-starter-security</artifactId>
<version>4.2.3.RELEASE</version>
</dependency> </dependency>
</dependencies> </dependencies>
......
//package com.us.example.config; package com.us.example.config;
//
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity;
//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//
//@Configuration @Configuration
//@EnableWebSecurity @EnableWebSecurity
//public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
// @Override @Override
// protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
// http http
// .authorizeRequests() .authorizeRequests()
// .antMatchers("/","/login").permitAll()//1根路径和/login路径不拦截 .antMatchers("/","/login").permitAll()//根路径和/login路径不拦截
// .anyRequest().authenticated() .anyRequest().authenticated()
// .and() .and()
// .formLogin() .formLogin()
// .loginPage("/login") //2登陆页面 .loginPage("/login") //2登陆页面路径为/login
// .defaultSuccessUrl("/chat") //3登陆成功转向该页面 .defaultSuccessUrl("/chat") //3登陆成功转向chat页面
// .permitAll() .permitAll()
// .and() .and()
// .logout() .logout()
// .permitAll(); .permitAll();
// } }
//
// //4 //4在内存中配置两个用户 wyf 和 wisely ,密码和用户名一致,角色是 USER
// @Override @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception { protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth auth
// .inMemoryAuthentication() .inMemoryAuthentication()
// .withUser("wyf").password("wyf").roles("USER") .withUser("wyf").password("wyf").roles("USER")
// .and() .and()
// .withUser("wisely").password("wisely").roles("USER"); .withUser("wisely").password("wisely").roles("USER");
// } }
// //5忽略静态资源的拦截 //5忽略静态资源的拦截
// @Override @Override
// public void configure(WebSecurity web) throws Exception { public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/resources/static/**"); web.ignoring().antMatchers("/resources/static/**");
// } }
//
//} }
\ No newline at end of file \ No newline at end of file
...@@ -18,15 +18,21 @@ public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ ...@@ -18,15 +18,21 @@ public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { //endPoint 注册协议节点,并映射指定的URl public void registerStompEndpoints(StompEndpointRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.addEndpoint("/endpointWisely").withSockJS();//注册一个Stomp 协议的endpoint,并指定 SockJS协议。 //注册一个Stomp 协议的endpoint,并指定 SockJS协议
// registry.addEndpoint("/endpointChat").withSockJS(); registry.addEndpoint("/endpointWisely").withSockJS();
//注册一个名字为"endpointChat" 的endpoint,并指定 SockJS协议。 点对点-用
registry.addEndpoint("/endpointChat").withSockJS();
} }
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(message broker) public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(message broker)
registry.enableSimpleBroker("/topic"); //广播式应配置一个/topic 消息代理 //广播式应配置一个/topic 消息代理
// registry.enableSimpleBroker("/queue","/topic"); //2 registry.enableSimpleBroker("/topic");
//点对点式增加一个/queue 消息代理
registry.enableSimpleBroker("/queue","/topic");
} }
} }
...@@ -23,6 +23,9 @@ import java.security.Principal; ...@@ -23,6 +23,9 @@ import java.security.Principal;
public class WebSocketController { public class WebSocketController {
@Autowired @Autowired
private WebSocketService ws; private WebSocketService ws;
@Autowired
private SimpMessagingTemplate messagingTemplate;
//http://localhost:8080/ws //http://localhost:8080/ws
@MessageMapping("/welcome")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。 @MessageMapping("/welcome")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
...@@ -41,19 +44,24 @@ public class WebSocketController { ...@@ -41,19 +44,24 @@ public class WebSocketController {
return "is ok"; return "is ok";
} }
// @Autowired @MessageMapping("/chat")
// private SimpMessagingTemplate messagingTemplate;//1 //在springmvc 中可以直接获得principal,principal 中包含当前用户的信息
// public void handleChat(Principal principal, Message message) {
// @MessageMapping("/chat")
// public void handleChat(Principal principal, String msg) { //2 /**
// if (principal.getName().equals("wyf")) {//3 * 此处是一段硬编码。如果发送人是wyf 则发送给 wisely 如果发送人是wisely 就发送给 wyf。
// messagingTemplate.convertAndSendToUser("wisely", */
// "/queue/notifications", principal.getName() + "-send:" if (principal.getName().equals("wyf")) {
// + msg); //通过convertAndSendToUser 向用户发送信息,
// } else { // 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身
// messagingTemplate.convertAndSendToUser("wyf",
// "/queue/notifications", principal.getName() + "-send:" messagingTemplate.convertAndSendToUser("wisely",
// + msg); "/queue/notifications", principal.getName() + "-send:"
// } + message.getName());
// } } else {
messagingTemplate.convertAndSendToUser("wyf",
"/queue/notifications", principal.getName() + "-send:"
+ message.getName());
}
}
} }
...@@ -11,7 +11,9 @@ import org.springframework.stereotype.Service; ...@@ -11,7 +11,9 @@ import org.springframework.stereotype.Service;
@Service @Service
public class WebSocketService { public class WebSocketService {
@Autowired @Autowired
//使用SimpMessagingTemplate 向浏览器发送消息
private SimpMessagingTemplate template; private SimpMessagingTemplate template;
public void sendMessage() throws Exception{ public void sendMessage() throws Exception{
......
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<head>
<title>Home</title>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
</head>
<body>
<p>
聊天室
</p>
<form id="wiselyForm">
<textarea rows="4" cols="60" name="text"></textarea>
<input type="submit"/>
</form>
<script th:inline="javascript">
$('#wiselyForm').submit(function(e){
e.preventDefault();
var text = $('#wiselyForm').find('textarea[name="text"]').val();
sendSpittle(text);
});
//链接endpoint名称为 "/endpointChat" 的endpoint。
var sock = new SockJS("/endpointChat");
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
/**
 订阅了/user/queue/notifications 发送的消息,这里雨在控制器的 convertAndSendToUser 定义的地址保持一致,

* 这里多用了一个/user,并且这个user 是必须的,使用user 才会发送消息到指定的用户。

* */
stomp.subscribe("/user/queue/notifications", handleNotification);
});
function handleNotification(message) {
$('#output').append("<b>Received: " + message.body + "</b><br/>")
}
function sendSpittle(text) {
stomp.send("/chat", {}, JSON.stringify({ 'name': text }));//3
}
$('#stop').click(function() {sock.close()});
</script>
<div id="output"></div>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<meta charset="UTF-8" />
<head>
<title>登陆页面</title>
</head>
<body>
<div th:if="${param.error}">
无效的账号和密码
</div>
<div th:if="${param.logout}">
你已注销
</div>
<form th:action="@{/login}" method="post">
<div><label> 账号 : <input type="text" name="username"/> </label></div>
<div><label> 密码: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登陆"/></div>
</form>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment