springboot整合websocket实现聊天室功能

一、首先pom依赖



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.4.RELEASE
         
    
    com.example
    chat
    0.0.1-SNAPSHOT
    war
    chat
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-devtools
            true
        
        
            org.springframework.boot
            spring-boot-starter-websocket
            2.1.4.RELEASE
        
        
        
            org.webjars.npm
            mdui
            0.4.0
        
        
            org.webjars
            webjars-locator-core
            0.37
        
        
            org.webjars
            sockjs-client
            1.1.2
        
        
            org.webjars
            stomp-websocket
            2.3.3-1
        
        
            org.webjars
            jquery
            3.4.0
        
        
            com.alibaba
            fastjson
            1.2.49
        

        
        
            org.springframework.boot
            spring-boot-starter-tomcat
            
            provided
        
    

    
        chatroom
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

二、websocket配置类

package com.example.chat.config;

import org.springframework.context.annotation.Configuration;
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;

/**
 * @Author: 韩老魔
 * ebsocket配置类
 * @Date: 2019/4/17 0017 17:02
 */
@Configuration
@EnableWebSocketMessageBroker//使用此注解来标识使能WebSocket的broker.即使用broker来处理消息.
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{

    /**
     * 连接路径配置
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        /*
         * 路径"/websocket"被注册为STOMP端点,对外暴露,客户端通过该路径获取与socket的连接
         */
        registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 服务端接收消息路径配置
     * @param config
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
    //消息代理的前缀 该路径消息会被代理通过广播方式发给客户端(广播路径)
        config.enableSimpleBroker("/topic");

        /*
         * 过滤该路径集合发送过来的消息,被@MessageMapping注解的方法接收处理具体决定广播还是单点发送到客户端
         */
        config.setApplicationDestinationPrefixes("/app","/queue");
    }

}

三、消息实体类

package com.example.chat.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @Author: 韩老魔
 * 消息类
 * @Date: 2019/4/17 0017 19:40
 */

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Message {
    private String name; //发送人
    private String content; //发送消息
    private String date;
}

四、控制器

package com.example.chat.controller;

import com.example.chat.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author: 韩老魔
 * @Date: 2019/4/17 0017 19:26
 */
@Controller
public class WebSocketController {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /*页面入口*/
    @RequestMapping("/chat")
    public String chat() {
        return "chat";
    }

    /**
     * 群发
     * @param message
     * @return
     * @throws Exception
     */
    @MessageMapping("/hello") //接收/app/hello路径发来的信息:/app被@MessageMapping拦截,/hello被注解内参数拦截
    @SendTo("/topic/greetings")//接收上面路径发来的消息后在发送到广播的路径上 即会被代理进行广播群发
    public Message messageHandling(Message message) throws Exception {
        return message;
    }

}

五、设置定时器(写着玩的 可以不要)

package com.example.chat.job;

import com.example.chat.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: 韩老魔
 * @Date: 2019/4/17 0017 20:27
 */
@Configuration
public class MyJob {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Scheduled(fixedRate = 10000)
    public void send() {

        SimpleDateFormat sdf=new SimpleDateFormat();
        String formatDate = sdf.format(new Date());
        messagingTemplate.convertAndSend("/topic/greetings", new Message("定时任务:", "检测通信", formatDate));
    }
}

六、yml配置

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
    cache: false #关闭缓存
server:
  port: 8081
  servlet:
    context-path: /chatroom

七、前端模板




    吐槽
    
    
    

    
    
    

    
    

    
    
    
    




kicol的聊天室 exit

八、启动后访问 http://localhost:8081/chatroom/chat

a.png

你可能感兴趣的:(springboot整合websocket实现聊天室功能)