栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot+websockt实现简易单聊,群发消息

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot+websockt实现简易单聊,群发消息

springboot+websockt实现简易单聊,群发消息

实现效果:



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




    
    用户登陆


欢迎来的简易聊天系统

用户名:
密码:



    
    聊天信息
    
    
    

聊天系统

欢迎您:

模拟发送消息控制台



    
    控制台


发送消息给admin
发送消息给zhangsan
群发消息

JS文件

项目下载

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769687.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号