基于spingboot的websocket订阅、广播、多人聊天室示例

概述

基于spingboot的websocket多人聊天系统。包括订阅,广播、点对点单人聊天,多人聊天室功能。

详细

一、运行效果

简单示例

广播

单人聊天

多人聊天室

二、相关代码

websocket配置

复制代码
package com.iamgpj.demowebsocket.config;
 
import com.iamgpj.demowebsocket.v4.SocketChannelInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
 
import javax.websocket.server.ServerEndpointConfig;
 
/**
 * @author Ives
 * @date 2020/4/20 13:51
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends ServerEndpointConfig.Configurator implements WebSocketMessageBrokerConfigurer {
 
    /**
     * 注册端点,发布或者订阅消息的时候需要连接此端点
     * addEndpoint websocket的端点,客户端需要注册这个端点进行链接
     * setAllowedOrigins 非必须,*表示允许其他域进行连接,跨域
     * withSockJS 允许客户端利用sockjs进行浏览器兼容性处理
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws/endpoints-websocket")
                //.setAllowedOrigins("*")
                .withSockJS();
    }
 
    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 设置服务器广播消息的基础路径
        registry.enableSimpleBroker("/topic", "/user");
        // 设置客户端订阅消息的基础路径
        registry.setApplicationDestinationPrefixes("/app");
    }
 
 
    /** 配置频道拦截器,用于聊天室 */
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new SocketChannelInterceptor());
    }
}

聊天室程序

复制代码
package com.iamgpj.demowebsocket.v4;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author Ives
 * @date 2020/4/21 11:13
 */
@Service
@Slf4j
public class ChatRoomService {
 
    @Autowired
    private SimpMessagingTemplate template;
 
    /**
     * 模拟数据库中存储的用户
     */
    public static Map<String, String> userMap = new HashMap<>();
    /**
     * 保存当前在线用户
     * 实际应该存储于redis等可持久化缓存服务器中,做到数据共享
     */
    public static Map<String, String> onlineUserMap = new HashMap<>();
 
    /** 初始化数据 */
    static {
        userMap.put("张三", "111111");
        userMap.put("李四", "111111");
        userMap.put("王五", "111111");
        userMap.put("赵六", "111111");
        userMap.put("陈七", "111111");
    }
 
    /**
     * 每两秒给客户端推送当前在线用户
     */
    @Scheduled(fixedRate = 2000)
    public void pushOnlineUser() {
        Collection<String> users = onlineUserMap.values();
        log.info("【聊天室在线用户】={}", users);
        template.convertAndSend("/topic/onlineUser", users);
    }
 
 
    /**
     * 推送聊天消息
     * @param inMessage 内容
     */
    public void pushChatRoom(InMessage inMessage) {
        OutMessage outMessage = new OutMessage();
        BeanUtils.copyProperties(inMessage, outMessage);
        outMessage.setPushTime(LocalDateTime.now());
        template.convertAndSend("/topic/chatRoom", outMessage);
    }
}

三、代码结构

四、相关说明

1、项目前段使用bootstrap框架,使用maven引入webjars作为样式文件。

2、访问路径分别为

http://localhost:8080/v1/index.html

http://localhost:8080/v2/index.html

http://localhost:8080/v3/tom.html

http://localhost:8080/v3/jerry.html

http://localhost:8080/v4/index.html

3、聊天室请分别使用不同浏览器登录测试。登录名可以为,张三、李四、王五、赵六....

相关推荐
零基础的修炼几秒前
Linux网络---网络层
运维·服务器·网络
开开心心就好9 分钟前
键盘改键工具免安装,自定义键位屏蔽误触
java·网络·windows·随机森林·计算机外设·电脑·excel
旖旎夜光1 小时前
Linux(13)(上)
linux·网络
郝学胜-神的一滴1 小时前
深入解析Linux网络编程之bind函数:从基础到实践的艺术
linux·服务器·网络·c++·websocket·程序人生
pythonchashaoyou1 小时前
静态住宅ip是什么,静态住宅IP选型全解
网络·网络协议·tcp/ip
相思难忘成疾2 小时前
通向HCIP之路:第三步:动态路由协议OSPF(全)
服务器·网络·智能路由器·hcip
REDcker2 小时前
HTTP请求数据包流转详解:localhost、127.0.0.1、公网 IP、公网域名访问时的数据流转
网络·tcp/ip·http
Godspeed Zhao2 小时前
现代智能汽车系统——网络
网络·汽车
未来之窗软件服务4 小时前
自己平台接入国家网络身份认证公共服务接入
网络·仙盟创梦ide·东方仙盟
要做一个小太阳4 小时前
华为Atlas 900 A3 SuperPoD 超节点网络架构
运维·服务器·网络·华为·架构