首先pom.xml文件
4.0.0 com.avicsafety im 0.0.1-SNAPSHOT jar service-im Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-websocket org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-security org.springframework.cloud spring-cloud-dependencies Dalston.RC1 pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
2. WebSocketConfig 设置了Socket 配置
@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/endpointWisely").withSockJS(); registry.addEndpoint("/endpointChat").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/queue","/topic"); }}
3. 配置了Security 和 3个账号
@Configuration@EnableWebSecuritypublic class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/","/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/chat") .permitAll() .and() .logout() .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("liudehua").password("zzz123").roles("USER") .and() .withUser("zhangmanyu").password("zzz123").roles("USER") .and() .withUser("guofucheng").password("zzz123").roles("USER"); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/static/**"); } }
4. 服务器接受到消息 并发给指定的人
@Controller@SpringBootApplicationpublic class WebSocketApplication { @RequestMapping("/login") public void login(){} @RequestMapping("/chat") public void chat(){} @Autowired private SimpMessagingTemplate messagingTemplate; @MessageMapping("/chat") public void handleChat(Principal principal, String username, String message) { messagingTemplate.convertAndSendToUser(username,"/queue/notifications", principal.getName() + "-say:" + message); } public static void main(String[] args) { SpringApplication.run(WebSocketApplication.class, args); }}