• WebSocket实现聊天功能


    使用SpringBoot + WebSocket 实现模拟QQ聊天功能

    登录界面展示

    登录界面模仿QQ登录操作,支持拖动、最小化和关闭

    聊天界面展示

    登录后的右侧显示在线用户,右下方显示在线用户的登录日志
    窗口支持拖动、关闭操作


    发送消息界面展示

    在线用户实现及时聊天功能,可以对指定用户发起聊天(实现点对点的消息推送功能)
    支持消息的本地缓存,聊天内容不会因为页面的刷新、关闭、退出登录等操作而丢失(消息只是做了简单缓存),清理浏览器缓存数据时消息数据便会丢失。

    点对点消息推送,实现一对一的即时通信功能

    Demo的目录代码

    该Demo主要使用的是 SpringBoot + WebSocket 技术实现

    在这里插入图片描述

    下面是Demo的后端代码实现及说明

    创建SpringBoot项目,导入依赖

    项目pom依赖配置

    	
    		1.8
    		1.8
    		1.8
    		UTF-8
    		UTF-8
    	
    
    	
    		
    		
    			org.springframework.boot
    			spring-boot-starter-web
    		
    
    		
    		
    			org.springframework.boot
    			spring-boot-starter-websocket
    		
    
    		
    		
    			org.springframework.boot
    			spring-boot-devtools
    			true
    			true
    		
    
    		
    		
    			org.apache.commons
    			commons-lang3
    		
            
            
    			cn.hutool
    			hutool-all
    			5.7.16
    		
    
    		
    		
    			org.slf4j
    			slf4j-api
    		
    		
    			org.slf4j
    			slf4j-log4j12
    		
    
    		
    		
    			com.alibaba
    			fastjson
    			1.2.55
    		
    	
    
    	
    		
    		
    			
    				org.springframework.boot
    				spring-boot-maven-plugin
    			
    		
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    项目配置文件说明

    application.properties

    # 项目名称
    spring.application.name=websocket-chatroom
    # 配置资源路径
    spring.resource.static-locations=classpath:/static/
    # 视图前缀配置
    spring.mvc.view.prefix=/chat/
    # 视图后缀配置
    spring.mvc.view.suffix=.html
    ###########################【热部署】#########################
    # 重启目录
    spring.devtools.restart.additional-paths=src/main/java
    # 设置开启热部署
    spring.devtools.restart.enabled=true
    # 设置字符集
    spring.freemarker.charset=utf-8
    # 页面不加载缓存,修改后立即生效
    spring.freemarker.cache=false
    # 服务端口配置
    server.port=80
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    application.yml

    spring:
      resource:
        static-locations: classpath:/static/    
      application:
        name: websocket-chatroom
      mvc:
        view:
          suffix: .html
          prefix: /chat/
      devtools: 
        restart:
          additional-paths: src/main/java
          enabled: true
      freemarker: 
        charset: utf-8
        cache: false
    server:
      port: 80
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    项目的配置类说明

    WebConfig.java

    WebConfig 配置类

    配置后项目启动时,访问默认项目路径时,会跳转到该类指定的页面中

    /**
     * @title web配置类 设置默认访问页面
     * @author 陌路
     * @date 2022-04-16
     * @apiNote 配置默认页面
     */
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    	/**
    	 * 自定义静态路径,spring.resource.static-locations=classpath:/static/
    	 */
    	@Override
    	public void addViewControllers(ViewControllerRegistry registry) {
    		registry.addViewController("/").setViewName("/chat/login");
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    WebSocketConfig.java

    使用WebSocket前首先配置 @ServerEndpoint

    • 首先需要注入 ServerEndpointExporter ,

    • 这个bean会自动注册使用 @ServerEndpoint 注解来声明WebSocket endpoint。

    • 注意:如果使用独立的Servlet容器,而不是直接使用SpringBoot内置容器,就不需要注入 ServerEndpointExporter,因为他将由容器自己提供和管理。

    /**
     * @Desc 	首先需要注入 ServerEndpointExporter , 
     * 			这个bean会自动注册使用 @ServerEndpoint 的注解来声明WebSocket endpoint。
     *     注意:如果使用独立的Servlet容器,而不是直接使用SpringBoot内置容器,就不需要注入
     *       	ServerEndpointExporter,因为他将有容器自己提供和管理。
     * @author 陌路
     * @date 2022-04-16
     */
    @Configuration
    public class WebSocketConfig {
    	/**
    	 * @title 扫描注册使用 @ServerEndpoint 注解的类
    	 */
    	@Bean
    	public ServerEndpointExporter serverEndpointExporter() {
    		return new ServerEndpointExporter();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    GetHttpSessionConfigurator.java

    该类可以在建立连接后存放HttpSession,方便后续的使用

    用户建立连接时,通过 EndpointConfig 获取存在 session 中的用户数据

    /**
     * @tite 用来获取HttpSession对象.
     * @author 陌路
     * @date 2022-04-16
     */
    public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
    	/**
    	 * @title 该配置可以在不手动传入HttpSession的情况下在websocket服务类中使用
    	 */
    	@Override
    	public void modifyHandshake(ServerEndpointConfig sec, 
                                    HandshakeRequest request, 
                                    HandshakeResponse response) {
    		// 获取httpsession对象
    		HttpSession httpSession = (HttpSession) request.getHttpSession();
    		// 存放httpsession对象
    		Map userProperties = sec.getUserProperties();
    		userProperties.put(HttpSession.class.getName(), httpSession);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    创建用户对象实体

    /**
     * (User)实体类
     * @author 陌路
     * @since 2022-04-16
     */
    @Data
    public class User implements Serializable {
        private static final long serialVersionUID = -31513108721728277L;
        /** 用户id */
    	private String userId;
        /**  用户名 */
        private String username;
        /** 用户手机号 */
        private String phone;
        /** 用户密码 */
        private String password;
        public User(String userId, String username, String password, String phone) {
    		this.userId = userId;
    		this.username = username;
    		this.password = password;
    		this.phone = phone;
    	}
        public User() {
        }
    }  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    创建数据信息对象

    使用数据信息对象来模拟数据存储数据,实现用户的登录和注册

    import cn.hutool.core.lang.Validator;
    import cn.molu.app.pojo.User;
    import cn.molu.app.vo.R;
    /**
     * @title 模拟数据库user表
     * @Desc 模拟数据库数据,用户登录校验
     * @author 陌路
     * @date 2022-04-16
     */
    public class UserData {
    	/**
    	 * 构造用户数据 模拟数据库用户
    	 */
    	public static Map userMap = new HashMap();
    	static {
            //userMap.key=phone, userMap.value=user(id, name, password, phone);
    		userMap.put("150******67", new User("001", "jack", "123456", "150******67"));
    		userMap.put("135******88", new User("002", "mary", "123456", "135******88"));
    		userMap.put("136******66", new User("003", "tom", "123456", "136******66"));
    		userMap.put("159******21", new User("004", "tim", "123456", "159******21"));
    		userMap.put("188******88", new User("005", "jenny", "123456", "188******88"));
    		userMap.put("177******14", new User("006", "admin", "123456", "177******14"));
    		userMap.put("176******67", new User("007", "lover", "123456", "176******67"));
    		userMap.put("150******83", new User("008", "molu", "123456", "150******83"));
    	}
    	/**
    	 * @Title 根据手机号获取用户信息
    	 * @return User
    	 */
    	public static User loginByPhone(String phone) {
    		boolean mobile = Validator.isMobile(phone);
    		if (!mobile) {
    			return null;
    		}
    		User user = userMap.get(phone);
    		if (ObjectUtils.isBlank(user)) {
    			return null;
    		}
    		return user;
    	}
    	/**
    	 * @Title 用户注册
    	 * @return R
    	 */
    	public static R register(HttpServletResponse res, User user) {
    		if (null == user) {
    			return R.err("请输入手机号、用户名和密码!");
    		}
    		String phone = user.getPhone();
    		String username = user.getUsername();
    		String password = user.getPassword();
    		ObjectUtils.checkNull(res, "手机号、用户名和密码不能为空!", phone, username, password);
    		user.setUserId(String.format("%03d", String.valueOf(userMap.size() + 1)));
    		userMap.put(phone, user);
    		return R.ok("注册成功!");
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    数据响应实体类

    响应数据结果,存储用户基本数据,过滤掉用户的重要信息

    /**
     * @Desc 数据的响应类.
     * @author 陌路
     * @date 2022-04-16 上午10:53:15
     */
    @Data
    public class Result {
    	/** 响应标志,成功/失败 */
    	private boolean flag;
    	/** 响应给前台的消息 */
    	private String message;
    	/** 用户名 */
    	private String username;
    	/** 用户id */
    	private String userId;
    	/** 日期时间 */
    	private String dateStr;
    
    	public void setDateStr(Date date) {
    		this.dateStr = dateFormat(date);
    	}
    
    	public Result() {
    		super();
    	}
    
    	public static String dateFormat(Date date) {
    		return ObjectUtils.dateFormat(date);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    消息接收和响应类

    用于接收和返回数据前台数据

    /**
     * @title 服务端发送给客户端的消息.
     */
    public class ResultMessage {
    	/** 是否是系统消息 */
    	private Boolean systemMsgFlag;
    	/** 发送方姓名 */
    	private String fromName;
    	/** 发送方id */
    	private String fromId;
    	/** 接收方姓名 */
    	private String toName;
    	/** 接收方id */
    	private String toId;
    	/** 发送的数据 */
    	private Object message;
    	/** 接收到消息的日期时间 */
    	private String dateStr;
    
    	public void setDateStr(String dateStr) {
    		this.dateStr = dateStr;
    	}
    
    	public String getDateStr(Date date) {
    		if (date == null) {
    			date = new Date();
    		}
    		return dateFormat(date);
    	}
    
    	public void setDateStr() {
    		this.dateStr = dateFormat(new Date());
    	}
    
    	public void setDateStr(Date date) {
    		if (date == null) {
    			date = new Date();
    		}
    		this.dateStr = dateFormat(date);
    	}
    
    	public ResultMessage() {
    		super();
    	}
        
    	public static String dateFormat(Object date) {
    		return ObjectUtils.dateFormat(date);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    WS核心服务类

    webSocket 的核心服务类,建立连接、发送消息、推送通知、关闭连接释放资源、消息处理等。。。

    /**
     * @Desc 注解 @ServerEndpoint 配置对外暴露访问地址,外部访问格式为(ws://localhost:80/webSocket/001)
     * @author 陌路
     * @date 2022-04-16
     */
    @Component
    @ServerEndpoint(value = "/webSocket/{userId}", configurator = GetHttpSessionConfigurator.class)
    public class ChatEndpoint {
    	private final static Logger LOGGER = LogManager.getLogger(ChatEndpoint.class);
    	/** 声明一个线程安全的全局Map对象,用来存储每一个用户的Session对象 */
    	private static Map onLineUsers = new ConcurrentHashMap();
    	/** 缓存用户数据 */
    	public static Map cacheUser = new HashMap();
        
    	/** 获取HttpSession中的用户名 */
    	private HttpSession httpSession;
    
    	/**
    	 * @Title 连接建立时,会调用该方法
    	 */
    	@OnOpen
    	public void onOpen(Session session, EndpointConfig endpointConfig) {
            // 获取GetHttpSessionConfigurator中存放的HttpSession
    		Map userProperties = endpointConfig.getUserProperties();
    		HttpSession httpSession = (HttpSession) userProperties.get(HttpSession.class.getName());
    		this.httpSession = httpSession;
    		String username = ObjectUtils.getStr(httpSession.getAttribute("username")) ;
    		String userId = ObjectUtils.getStr(httpSession.getAttribute("userId"));
            // 如果用户名和用户id为空,则直接返回
    		if (ObjectUtils.isEmpty(username,userId)) {
    			return;
    		}
            LOGGER.info("{}	建立了连接。。。", username);
            Result res = new Result();
    		res.setUserId(userId);
    		res.setUsername(username);
    		// 缓存数据
    		onLineUsers.put(userId, session);
    		cacheUser.put(userId, res);
    		// 组织消息体数据,将数据推送给所有在线用户
    		String message = getSysMessage(getusers());
    		// 调用方法进行系统消息的推送
    		broadcastAllUsers(message);
    		LOGGER.info("推送系统消息:{}	", message);
    	}
    
    	/**
    	 * @Title 接收到客户端发送的数据时,会调用此方法
    	 */
    	@OnMessage
    	public void onMessage(String message, Session session) throws IOException {
    		LOGGER.info("接收到消息:{}", message);
    		if (StringUtils.isBlank(message)) {
    			return;
    		}
            // 心跳检测机制
    		if ("PING".toUpperCase().equals(message.toUpperCase())) {
    			heartCheck(session);
    			return;
    		}
    		LOGGER.info("接收到好友的消息:{}", message);
    		ResultMessage msgObj = JSON.parseObject(message, ResultMessage.class);
            // 消息接收人id
    		String toId = msgObj.getToId();
            // 获取消息体内容
    		String text = ObjectUtils.getStr(msgObj.getMessage());
    		// 获取推送指定用户数据
    		String resultMessage = getMessage(msgObj, text);
    		LOGGER.info("接收到好友发来的数据:{}", resultMessage);
    		// 点对点发送数据(给指定用户发送消息)
    		Session toSession = onLineUsers.get(toId);
    		if (toSession != null && toSession.isOpen()) {
                Basic basicRemote = toSession.getBasicRemote();
                basicRemote.sendText(resultMessage);
    		}
    	}
    
    	/**
    	 * @title 连接关闭时,调用此方法
    	 */
    	@OnClose
    	public void onClose(Session session) {
    		if (httpSession == null) {
    			return;
    		}
    		String username = ObjectUtils.getStr(httpSession.getAttribute("username"));
    		String userId = ObjectUtils.getStr(httpSession.getAttribute("userId"));
    		if (StringUtils.isBlank(userId)) {
    			return;
    		}
    		LOGGER.info("{}:关闭了连接。。。", username);
    		// 移除已关闭连接的用户
    		onLineUsers.remove(userId);
            // 移除缓存的用户数据
    		cacheUser.remove(userId);
    		LOGGER.info("已从onLineUsers移除:{},从cacheUser中移除:{}", username, username);
    		String message = getSysMessage(getusers());
    		// 设置已关闭连接的用户数据在HttpSession域中有效时间
    		httpSession.setMaxInactiveInterval(1800);
    		broadcastAllUsers(message);
            LOGGER.info("关闭连接,推送内容:{}", message);
    	}
    
    	/**
    	 * @title 出现错误时调用改方法
    	 */
    	@OnError
    	public void onError(Session session, Throwable error) {
    		LOGGER.info("连接出错了......{}", error);
    	}
        
    	/**
    	 * @title 消息的推送,将消息推送给所有在线用户
    	 * @param message
    	 */
    	private void broadcastAllUsers(String message) {
    		try {
    			// 将消息推送给所有的在线用户
    			Set ids = getIds();
    			LOGGER.info("onLineUsers的所有id:{}", ids);
    			for (String id : ids) {
    				Session session = onLineUsers.get(id);
    				Result result = cacheUser.get(id);
    				LOGGER.info("获取到用户信息:{}", result);
    				// 判断用户是否是连接状态
    				if (session.isOpen()) {
    					session.getBasicRemote().sendText(message);
    				}
    			}
    			LOGGER.info("给{}推送了{}", getIds(), message);
    		} catch (Exception e) {
    			LOGGER.error("广播发送系统消息失败!{}", e);
    			e.printStackTrace();
    		}
    	}
        
        /**
    	 * @title 组织消息内容
    	 */
    	public static String getMessage(ResultMessage resultMessage, String message) {
    		resultMessage.setSystemMsgFlag(false);
    		resultMessage.setMessage(message);
    		ObjectMapper objectMapper = new ObjectMapper();
    		try {
    			return objectMapper.writeValueAsString(resultMessage);
    		} catch (JsonProcessingException e) {
    			e.printStackTrace();
    		}
    		return "";
    	}
        
        /**
    	 * @Title 组织系统推送数据信息
    	 * @return String
    	 */
    	public static String getSysMessage(Collection collection) {
    		ResultMessage resultMessage = new ResultMessage();
    		resultMessage.setSystemMsgFlag(true);
    		resultMessage.setMessage(collection);
    		ObjectMapper objectMapper = new ObjectMapper();
    		try {
    			return objectMapper.writeValueAsString(resultMessage);
    		} catch (JsonProcessingException e) {
    			e.printStackTrace();
    		}
    		return "";
    	}
        
        /**
    	 * @Title 心跳检测机制
    	 */
    	public static void heartCheck(Session session) {
    		try {
    			Map params = new HashMap();
    			params.put("type", "PONG");
    			session.getAsyncRemote().sendText(JSON.toJSONString(params));
    			LOGGER.info("应答客户端的消息:{}", JSON.toJSONString(params));
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
        
        
    	/**
    	 * @title 获取所有在线用户的用户id
    	 * @return Set
    	 */
    	private Set getIds() {
    		return ChatEndpoint.onLineUsers.keySet();
    	}
    
    	/**
    	 * @title 获取所有在线用户,如果是系统消息就返回这个
    	 * @return Set
    	 */
    	private Collection getusers() {
    		return cacheUser.values();
    	}
    
    	/**
    	 * @title 格式化Date类型的数据
    	 * @param date
    	 * @return yyyy-MM-dd HH:mm:ss
    	 */
    	public static String dateFormat(Date date) {
    		return ObjectUtils.dateFormat(date);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208

    后台控制器接口

    后端访问接口

    @Controller
    @RequestMapping("index")
    public class LoginController {
    
    	/**
    	 * 处理用户登录请求.
    	 * @param user    用户登录数据
    	 */
    	@ResponseBody
    	@PostMapping("/login")
    	public Result login(User user, HttpServletRequest req,HttpServletResponse res) {
            HttpSession session = req.getSession();
            ObjectUtils.checkNull(res,"请输入手机号和密码!",user,user.getPhone(),user.getPassword());
    		String phone = user.getPhone();
    		String password = user.getPassword();
            boolean mobile = Validator.isMobile(phone);
            Result result = new Result();
            if(!mobile){
                result.setMessage("手机号格式错误!");
    			result.setFlag(false);
                return result;
            }
    		try {
                User userData = UserData.loginByPhone(phone);
    			ObjectUtils.checkNull(res,userData,String.format("登录失败,未获取到%s的用户信息!", phone));
    			if (password.equals(userData.getPassword())) {
    				String username = userData.getUsername();
    				result.setFlag(true);
    				result.setMessage("登录成功!");
    				result.setUsername(username);
    				String userId = userData.getUserId();
    				result.setUserId(userId);
    				result.setDateStr(new Date());
    				session.setAttribute("username", username);
    				session.setAttribute("userId", userId);
    			} else {
    				result.setMessage("登录失败,密码输入错误!");
    				result.setFlag(false);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    			result.setMessage("登录失败!",e.getMessage());
    			result.setFlag(false);
    		}
    		return result;
    	}
    
    	/**
    	 * @Title 登录成功后跳转到聊天页面.
    	 * @return 跳转到聊天室,如果没有登录,则返回登录页面
    	 */
    	@GetMapping("/toChatroom")
    	public String toChatroom(HttpSession session) {
    		String username =ObjectUtils.getStr(session.getAttribute("username"));
    		if (StringUtils.isBlank(username)) {
    			return "login";
    		}
    		return "div";
    	}
    
    	/**
    	 * 登录成功后,获取session域中username值.
    	 * @param session
    	 */
    	@ResponseBody
    	@GetMapping("/getUsername")
    	public Map getUsername(HttpSession session) {
    		Map map = new HashMap();
    		String username = (String) session.getAttribute("username");
    		String userId = (String) session.getAttribute("userId");
    		map.put("flag", true);
    		map.put("username", username);
    		map.put("userId", userId);
    		return map;
    	}
        
        /**
         * @title 返回登录页面
         */
        @GetMapping(value = "/toIndex")
    	public String toIndexPage() {
    		return "login";
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84

    登录页面代码

    
    	
    		
    		登录
    		
    		
    		
    		
    		
    	
    	
    		
    WS     X

    找回密码
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    登录页面JS代码

    $(function() {
        $(".close").click(function() {
            $(".box").hide();
        });
        $("#loginFormBtn").click(function() {
            if (loginCheckData()) {
                login();
            }
        });
        $(".showPwd").bind("input propertychange", function() {
            if ($(this).prop("checked")) {
                $(".upwd").attr("type", "text");
            } else {
                $(".upwd").attr("type", "password");
            }
    	})
    });
    
    function login() {
        let params = {};
        params.phone = ml.empty($('.phone').val());
        params.password = ml.empty($('.upwd').val());
        params.flag = $("input[name='rememberMe']").prop("checked");
        $.post("/index/login", params, function(res) {
            if (res.flag) {
                ml.msgBox(res.message);
                location.href = "/index/toChatroom";
            } else {
                ml.msgBox(res.message, 5, 5);
            }
        }).error(function(err) {
            ml.msgBoxBtn(err.responseJSON.status + ":" + err.responseJSON.message, "错误提示");
        })
    }
    
    function loginCheckData() {
        let phone = ml.empty($('.phone').val());
        if (!phone || phone.length != 11) {
            ml.tips("请输入正确的手机号!", "phone");
            return false;
        }
        // 不可包含中文及中文字符
        let regZh = /[一-龥][ -〞?-?︰-﹄﹐-﹫!-?]/;
        //1.验证手机号 规则:第一位1,第二位是358中的一个,第三到十一位必须是数字。总长度11
        let reg = /^[1][358][0-9]{9}$/;
        if (!reg.test(phone) || regZh.test(phone)) {
            ml.tips("输入的手机号格式不正确!", "phone");
            return false;
        }
        let password = ml.empty($('.upwd').val());
        if (!password) {
            ml.tips("请输入密码!", "upwd");
            return false;
        }
        if (regZh.test(password)) {
            ml.tips("密码不可包含中文字符!", "upwd");
            return false;
        }
        if (password.length < 6) {
            ml.tips("密码必须为6~16个字符之间!", "upwd");
            return false;
        }
        let regPwd = /[A-Za-z0-9.!?]{12,30}/;
        if (!regPwd.test(password)) {
            ml.tips("密码仅支持数字、大小写字母和.!?符号", "upwd");
            return false;
        }
        //ml.msgBox("校验通过!");
        return true;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70

    聊天界面代码

    
    
    
    
    
    
    
    
    
    
    
    	
    X
    请选择好友聊天
      系统消息
        • 快去找朋友聊聊吧。。。
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26
        • 27
        • 28
        • 29
        • 30
        • 31
        • 32
        • 33
        • 34
        • 35
        • 36
        • 37
        • 38
        • 39
        • 40
        • 41
        • 42
        • 43
        • 44
        • 45
        • 46

        聊天界面JS代码

        let webObj = null;//全局WebSocket对象
        let lockReconnect = false; // 网络断开重连
        let wsCreateHandler = null; // 创建连接
        let username = null; // 当前登录人姓名
        let userId = null; //当亲登录人id
        let toName = null; //消息接收人姓名
        let toId = null;//消息接收人id
        $(function() {
        	$(".bg_change_size").remove();
        	// 在ajax请求开始前将请求设为同步请求:$.ajaxSettings.async = false。
        	// 在ajax请求结束后不要忘了将请求设为异步请求,否则其他的ajax请求也都变成了同步请求 $.ajaxSettings.async = true。
        	$.ajax({
        		async: false,
        		type: 'GET',
        		url: "/index/getUsername",
        		success: function(res) {
        			if (!res.userId || !res.username) {
        				location.href = '/index/toIndex';
        			}
        			username = res.username;
        			userId = res.userId;
        		}
        	});
        	// 创建webSocket对象
        	createWebSocket();
        	// 发送消息到服务器
        	$(".sendMsg").on("click", function() {
        		sendMessage();
        	})
        });
        
        /**
         * @title 创建连接
         */
        function createWebSocket() {
        	try {
        		// 获取访问路径,带有端口号:ws://localhost/webSocket/001
        		let host = window.location.host;
        		// 创建WebSocket连接对象
        		webObj = new WebSocket(`ws://${host}/webSocket/${userId}`);
        		// 加载组件
        		initWsEventHandle();
        	} catch (e) {
        		ml.msgBox("连接出错,正在尝试重新连接,请稍等。。。");
        		// 尝试重新连接服务器
        		reconnect();
        	}
        }
        
        /**
         * @title 初始化组件
         */
        function initWsEventHandle() {
        	try {
        		// 建立连接
        		webObj.onOpen = function(evt) {
        			onWsOpen(evt);
        			// 建立连接之后,开始传输心跳包
        			heartCheck.start();
        		};
        		// 传送消息
        		webObj.onmessage = function(evt) {
        			// 发送消息
        			onWsMessage(evt);
        			// 接收消息后 也需要心跳包的传送
        			heartCheck.start();
        		};
        		// 关闭连接
        		webObj.onclose = function(evt) {
        			// 关闭连接,可能是异常关闭,需要重新连接
        			onWsClose(evt);
        			// 尝试重新连接
        			reconnect();
        		};
        		// 连接出错
        		webObj.onerror = function(evt) {
        			// 连接出错
        			onWsError(evt);
        			// 尝试重新连接
        			reconnect();
        		}
        	} catch (e) {
        		if (e) {
        			conlog("catch", e);
        		}
        		ml.msgBox("初始化组件失败,正在重试,请稍后。。。");
        		// 尝试重新创建连接
        		reconnect();
        	}
        }
        
        /**
         * @title 建立连接
         */
        function onWsOpen(e) {
        	if (e.data) {
        		conlog("onWsOpen", e.data);
        	}
        	ml.msgBox("建立连接成功。。。");
        }
        
        /**
         * @title 传送消息内容
         */
        function onWsMessage(e) {
        	if (e.data) {
        		conlog("onWsMessage", e.data);
        	}
        	let jsonStr = e.data;
        	//接收到服务器推送的消息后触发事件
        	message(e);
        }
        
        /**
         * @title 关闭连接
         */
        function onWsClose(e) {
        	if (e.data) {
        		conlog("onWsClose", e.data);
        	}
        	ml.msgBox("连接关闭,尝试重新连接服务器,请稍侯。。。");
        	closeFun(e);
        }
        /**
         * @title 连接出错
         */
        function onWsError(e) {
        	ml.msgBox("连接出错,正在尝试重新连接服务器,请稍侯。。。" + e.data);
        }
        
        /**
         * @title 输出数据到控制台
         */
        function conlog(msg) {
        	conlog('', msg);
        }
        
        /**
         * @title 输出数据到控制台
         */
        function conlog(title, msg) {
        	let content = msg;
        	if (title) {
        		content = `${title}:${msg}`;
        	}
        	console.log(`${content}`);
        }
        
        /**
         * @title 异常处理
         * @Desc 处理可以检测到的异常,并尝试重新连接
         */
        function reconnect() {
        	if (lockReconnect) {
        		return;
        	}
        	conlog("reconnect");
        	ml.msgBox("正在尝试重新连接,请稍侯。。。");
        	lockReconnect = true;
        	// 没链接上会一直连接,设置延迟,避免过多请求
        	wsCreateHandler && clearTimeout(wsCreateHandler);
        	wsCreateHandler = setTimeout(function() {
        		ml.msgBox("正在重新连接。。。");
        		createWebSocket();
        		lockReconnect = false;
        		ml.msgBox("重连完成。。。");
        	}, 1000);
        }
        
        /**
         * @title 心跳检测
         * @Desc 网络中断,系统无法捕获,需要心跳检测实现重新连接
         */
        var heartCheck = {
        	// 在15s内若没收到服务端消息,则认为连接断开,需要重新连接
        	timeout: 15000, // 心跳检测触发时间
        	timeoutObj: null,
        	serverTimeoutObj: null,
        	// 重新连接
        	reset: function() {
        		clearTimeout(this.timeoutObj);
        		clearTimeout(this.serverTimeoutObj);
        		this.start();
        	},
        	// 开启定时器
        	start: function() {
        		let self = this;
        		this.timeoutObj && clearTimeout(this.timeoutObj);
        		this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        		this.timeoutObj = setTimeout(function() {
        			ml.msgBox("发送ping到后台服务。。。");
        			try {
        				webObj.send("PING");
        			} catch (e) {
        				ml.msgBox("发送ping异常。。。");
        			}
        			//内嵌定时器
        			self.serverTimeoutObj = setTimeout(function() {
        				// 若onclose方法会执行reconnect方法,我们只需执行close()就行,
                        // 若直接执行reconnect会触发onclose导致重连两次
        				ml.msgBox("没有收到后台数据,关闭连接。。。");
        				webObj.close();
        				//reconnect();
        			}, self.timeout);
        		}, this.timeout);
        	}
        };
        
        /**
         * @title 组织并解析数据
         */
        function message(e) {
        	//获取服务端推送过来的消息
        	let message = e.data;
        	// 将message转为JSON对象
        	let res = JSON.parse(message);
        	// 是否为系统消息
        	if (res.systemMsgFlag) {
        		let allNames = res.message;
        		//1. 好友列表展示   2. 系统推广
        		let userListStr = "";
        		let broadcastListStr = "";
        		let imgUrl = "../imgs/chatIc.png";
        		for (let user of allNames) {
        			if (user.userId != userId) {
        				userListStr += `
      • ${user.username}
      • `; broadcastListStr += `
      • ${user.dateStr}
        好友${user.username}上线了!
      • `; } } $(".friend-list").html(userListStr); $(".sys-msg").html(broadcastListStr); } else { // 不是系统消息 let msgText = res.message; let msg = `
      • ${msgText}
      • `; if (toId === res.fromId) { $(".chat-msg").append(msg); } let chatData = sessionStorage.getItem(res.fromId); if (chatData) { msg = chatData + msg; } sessionStorage.setItem(res.fromId, msg); $(".chat-main")[0].scrollTop = $(".chat-main")[0].scrollHeight; } } // 关闭连接 function closeFun(e) { let tips = `${new Date()}
        `; $(".sys-msg").html(`${tips}用户:${username}离开了`); } // 选择好友 function chatWith(id, name, obj) { toId = id; toName = name; $(".edit-msg").attr("disabled", false); $(".div-btn").show(); $(".chat-msg").show(); $(obj).addClass("selected-li").siblings().removeClass("selected-li"); let chatNow = `正在和${name}聊天`; $(".div-main-title").html(chatNow); $(".chat-msg").html(""); var chatData = sessionStorage.getItem(toId); if (chatData) { //渲染聊天数据到聊天区 $(".chat-msg").html(chatData); } $(".chat-main")[0].scrollTop = $(".chat-main")[0].scrollHeight; } /** * @title 组织和发送消息到服务器 */ function sendMessage() { // 发送消息 if (!toId || !toName) { ml.tips("sendMsg", "请选择好友..."); return; } let msg = $(".edit-msg").val(); if (!msg) { ml.tips("sendMsg", "请输入内容..."); return; } let img = ``; let li = $("
      • "); li.html(`${img}${msg}`); $(".chat-msg").append(li); $(".edit-msg").val(''); $(".chat-main")[0].scrollTop = $(".chat-main")[0].scrollHeight; let chatData = sessionStorage.getItem(toId); let liStr = `
      • ${img}${msg}
      • `; if (chatData) { liStr = chatData + liStr; } let jsonMessage = { "fromName": username, //消息发送人姓名 "fromId": userId, //消息发送人id "toName": toName, //消息接收人姓名 "toId": toId, //消息接收人id "message": msg //发送的消息内容 }; // 将消息存放到sessionStorage中 sessionStorage.setItem(toId, liStr); // 发送数据给服务器(消息发送格式为JSON格式) webObj.send(JSON.stringify(jsonMessage)); }
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 13
        • 14
        • 15
        • 16
        • 17
        • 18
        • 19
        • 20
        • 21
        • 22
        • 23
        • 24
        • 25
        • 26
        • 27
        • 28
        • 29
        • 30
        • 31
        • 32
        • 33
        • 34
        • 35
        • 36
        • 37
        • 38
        • 39
        • 40
        • 41
        • 42
        • 43
        • 44
        • 45
        • 46
        • 47
        • 48
        • 49
        • 50
        • 51
        • 52
        • 53
        • 54
        • 55
        • 56
        • 57
        • 58
        • 59
        • 60
        • 61
        • 62
        • 63
        • 64
        • 65
        • 66
        • 67
        • 68
        • 69
        • 70
        • 71
        • 72
        • 73
        • 74
        • 75
        • 76
        • 77
        • 78
        • 79
        • 80
        • 81
        • 82
        • 83
        • 84
        • 85
        • 86
        • 87
        • 88
        • 89
        • 90
        • 91
        • 92
        • 93
        • 94
        • 95
        • 96
        • 97
        • 98
        • 99
        • 100
        • 101
        • 102
        • 103
        • 104
        • 105
        • 106
        • 107
        • 108
        • 109
        • 110
        • 111
        • 112
        • 113
        • 114
        • 115
        • 116
        • 117
        • 118
        • 119
        • 120
        • 121
        • 122
        • 123
        • 124
        • 125
        • 126
        • 127
        • 128
        • 129
        • 130
        • 131
        • 132
        • 133
        • 134
        • 135
        • 136
        • 137
        • 138
        • 139
        • 140
        • 141
        • 142
        • 143
        • 144
        • 145
        • 146
        • 147
        • 148
        • 149
        • 150
        • 151
        • 152
        • 153
        • 154
        • 155
        • 156
        • 157
        • 158
        • 159
        • 160
        • 161
        • 162
        • 163
        • 164
        • 165
        • 166
        • 167
        • 168
        • 169
        • 170
        • 171
        • 172
        • 173
        • 174
        • 175
        • 176
        • 177
        • 178
        • 179
        • 180
        • 181
        • 182
        • 183
        • 184
        • 185
        • 186
        • 187
        • 188
        • 189
        • 190
        • 191
        • 192
        • 193
        • 194
        • 195
        • 196
        • 197
        • 198
        • 199
        • 200
        • 201
        • 202
        • 203
        • 204
        • 205
        • 206
        • 207
        • 208
        • 209
        • 210
        • 211
        • 212
        • 213
        • 214
        • 215
        • 216
        • 217
        • 218
        • 219
        • 220
        • 221
        • 222
        • 223
        • 224
        • 225
        • 226
        • 227
        • 228
        • 229
        • 230
        • 231
        • 232
        • 233
        • 234
        • 235
        • 236
        • 237
        • 238
        • 239
        • 240
        • 241
        • 242
        • 243
        • 244
        • 245
        • 246
        • 247
        • 248
        • 249
        • 250
        • 251
        • 252
        • 253
        • 254
        • 255
        • 256
        • 257
        • 258
        • 259
        • 260
        • 261
        • 262
        • 263
        • 264
        • 265
        • 266
        • 267
        • 268
        • 269
        • 270
        • 271
        • 272
        • 273
        • 274
        • 275
        • 276
        • 277
        • 278
        • 279
        • 280
        • 281
        • 282
        • 283
        • 284
        • 285
        • 286
        • 287
        • 288
        • 289
        • 290
        • 291
        • 292
        • 293
        • 294
        • 295
        • 296
        • 297
        • 298
        • 299
        • 300
        • 301
        • 302
        • 303
        • 304
        • 305
        • 306
        • 307
        • 308
        • 309
        • 310
        • 311
        • 312

        先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

      • 相关阅读:
        业务代码到底需不需要用多线程???
        java计算机毕业设计快递代收系统源码+系统+数据库+lw文档+mybatis+运行部署
        【如何去掉Unity点击运行时,Photon的警告弹窗】
        vue3 参数传递 props
        33李沐动手学深度学习v2/残差网络,ResNet
        8.3:加强堆的应用
        springboot-服务启动后访问只显示Initializing Spring DispatcherServlet ‘dispatcherServlet
        Java面向对象(高级)-- 类的成员之四:代码块
        提分必练!中创教育PMP全真模拟题分享来喽
        微信小程序组件、web-view、h5之间交互
      • 原文地址:https://blog.csdn.net/fwdwqdwq/article/details/126080468