实现效果:
1.导入maven依赖
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.2.RELEASE com.tangshuai springboot_websocket 1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-websocket org.springframework.boot spring-boot-starter-thymeleaf
2.新增用户类
package com.tangshuai.entity;
public class User{
String id;
String username;
String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3.创建基础数据
package com.tangshuai.entity;
import java.util.ArrayList;
import java.util.List;
public class UserList {
public static List getUser(){
List list=new ArrayList<>();
User user=new User();
user.setId("1");
user.setUsername("admin");
user.setPassword("123456");
list.add(user);
User user2=new User();
user2.setId("2");
user2.setUsername("zhangsan");
user2.setPassword("123456");
list.add(user2);
User user3=new User();
user3.setId("3");
user3.setUsername("lisi");
user3.setPassword("123456");
list.add(user3);
return list;
}
}
4.配置websocket
package com.tangshuai.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@EnableAsync
@Configuration
//表示开启使用STOMP协议来传输基于代理的消息
@EnableWebSocketMessageBroker
public class WsConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 注册一个端点,websocket的访问地址
registry.addEndpoint("/websocket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
//推送消息前缀
registry.enableSimpleBroker("/user/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
}
5.创建配置类,保存所有的session
package com.tangshuai.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
public class HttpSessionConfig {
private static final Map sessions = new HashMap<>();
public List getActiveSessions() {
return new ArrayList<>(sessions.values());
}
@Bean
public HttpSessionListener httpSessionListener() {
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent hse) {
sessions.put(hse.getSession().getId(), hse.getSession());
}
@Override
public void sessionDestroyed(HttpSessionEvent hse) {
sessions.remove(hse.getSession().getId());
}
};
}
}
6.创建service
package com.tangshuai.service;
public interface WsService {
void sendToUser(String toUserId,String concent);
}
package com.tangshuai.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class WsServiceImpl implements WsService{
@Autowired
SimpMessagingTemplate messagingTemplate;
@Async
@Override
public void sendToUser(String toUserId,String concent) {
// websocket通知 (/user/20/messCount)
messagingTemplate.convertAndSendToUser(toUserId, "/messCount", concent);
}
}
7.创建登陆Controller
package com.tangshuai.controller;
import com.tangshuai.entity.User;
import com.tangshuai.entity.UserList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class LogoinController {
@GetMapping("")
public String login (){
return "login.html";
}
@RequestMapping("/loginCheck")
public String loginCheck(String username, String password, HttpSession session, Model model){
System.out.println("登陆用户名:"+username);
List user = UserList.getUser();
for (User u : user) {
if(u.getUsername().equals(username) && u.getPassword().equals(password)){
session.setAttribute("user", u);
model.addAttribute("user", u);
System.out.println("=======================>【"+u.getUsername()+"】登陆成功!");
return "index.html";
}else{
System.out.println("=======================>用户名或密码错误!");
}
}
return "login.html";
}
}
8.创建发送消息Controller
package com.tangshuai.controller;
import com.tangshuai.config.HttpSessionConfig;
import com.tangshuai.entity.User;
import com.tangshuai.service.WsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class WebSocketController {
@Autowired
WsService wsService;
@Autowired
HttpSessionConfig httpSessionConfig;
@ResponseBody
@GetMapping("/reply")
public void reply() {
wsService.sendToUser("1","您好,用户【1】");
}
@ResponseBody
@GetMapping("/reply2")
public void reply2() {
wsService.sendToUser("2","您好,用户【2】");
}
@ResponseBody
@GetMapping("/broadcast")
public void broadcast(HttpSession session){
List activeSessions = httpSessionConfig.getActiveSessions();
System.out.println(activeSessions.size());
for (HttpSession httpSession : activeSessions) {
User u = (User) httpSession.getAttribute("user");
wsService.sendToUser(u.getId(),"所有用户您们好!");
}
}
@GetMapping("/home")
public String home(){
return "home.html";
}
}
9.创建登陆html
用户登陆
欢迎来的简易聊天系统
聊天信息
聊天系统
欢迎您:
模拟发送消息控制台


