springboot下使用websocket的案例

环境:idea,maven,springboot
首先需要三个js文件:jquery-3.3.1.min.js、sockjs.min.js、stomp.min.js
项目结构:
在这里插入图片描述
需要的jar包有

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

application.properties中的配置文件

  spring.freemarker.suffix=.html

config中的配置

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 配置WebSocket
 */
@Configuration
//注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    //注册STOMP协议的节点(endpoint),并映射指定的url
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册一个STOMP的endpoint,并指定使用SockJS协议
        registry.addEndpoint("/socket").setAllowedOrigins("*").withSockJS();
    }

    @Override
    //配置消息代理(Message Broker)
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //点对点应配置一个/user消息代理,广播式应配置一个/topic消息代理
        registry.enableSimpleBroker("/topic", "/user");
        //点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
//        registry.setUserDestinationPrefix("/user");
    }

MyJob中的内容:

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.time.LocalDateTime;

/**
 * @Description: java类作用描述
 * @Author: chenXingNan
 * @CreateDate: 2019/8/22$ 0:52$
 * @Version: 1.0
 */
@Configuration
public class MyJob {
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Scheduled(fixedRate = 1000)
    public void sendMessage(){
        System.out.println("来着服务端的消息");
        simpMessagingTemplate.convertAndSend("/topic/getResponse", System.currentTimeMillis());
    }
    @Scheduled(fixedRate = 1000)
    public void sendMessageToUser(){
        System.out.println("来着服务端给指定用户的消息");
        simpMessagingTemplate.convertAndSendToUser("1","/getResponse", LocalDateTime.now());
    }
}

IndexController中的内容:

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description: java类作用描述
 * @Author: chenXingNan
 * @CreateDate: 2019/8/22$ 0:24$
 * @Version: 1.0
 */
@Controller
@RequestMapping
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }
    @GetMapping("/user")
    public String user(long id, ModelMap modelMap){
        modelMap.addAttribute("id",id);
        return "user";
    }
}

index.html中的内容

<!DOCTYPE html>
<html>
<head>
    <title>socket测试</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="sockjs.min.js"></script>
    <script type="text/javascript" src="stomp.min.js"></script>
</head>
<body>
    <div id="msg"></div>
<script type="text/javascript">
    var stompClient = null;
    //加载完浏览器后  调用connect(),打开双通道
    $(function(){
    //打开双通道
    connect();
    });
    //强制关闭浏览器  调用websocket.close(),进行正常关闭
    window.onunload = function() {
        disconnect();
    }
    function connect(){
        var Id=1;
        var socket = new SockJS('http://localhost:8080/socket'); //连接SockJS的endpoint名称为"socket"
        stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
        stompClient.connect({},function(frame){//连接WebSocket服务端
            console.log('Connected:' + frame);
            // stompClient.subscribe("/user/"+Id+"/tocpic/getResponse",function(response){
            stompClient.subscribe('/topic/getResponse',function(response){
                var code=JSON.parse(response.body);
                showResponse(code);
                $("#msg").append(response.body+"<br/>")
            });
        });
    }
    //关闭双通道
    function disconnect(){
        if(stompClient != null) {
            stompClient.disconnect();
        }
        console.log("Disconnected");
    }
    function showResponse(message){
        var response = $("#name");
        response.append("<p>只有userID为"+message.id+"的人才能收到</p>");
    }
</script>
</body>
</html>

user.html中的内容

 <!DOCTYPE html>
<html>
<head>
    <title>socket测试</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="sockjs.min.js"></script>
    <script type="text/javascript" src="stomp.min.js"></script>
</head>
<body>
只有id为1的人能够收到消息
    <div id="msg"></div>

<script type="text/javascript">
    var stompClient = null; 
    //加载完浏览器后  调用connect(),打开双通道
    $(function(){   
    //打开双通道
    connect();
    });
    //强制关闭浏览器  调用websocket.close(),进行正常关闭
    window.onunload = function() {
        disconnect();
    }
    function connect(){
        // var Id='${id}';
        var Id='1';
        var socket = new SockJS('http://localhost:8080/socket'); //连接SockJS的endpoint名称为"socket"
        stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
        stompClient.connect({},function(frame){//连接WebSocket服务端         
            console.log('Connected:' + frame);
            stompClient.subscribe("/user/"+Id+"/getResponse",function(response){
            // stompClient.subscribe('/topic/getResponse',function(response){
                var code=JSON.parse(response.body);                                 
                showResponse(code);
                $("#msg").append(response.body+"<br/>")                  
            });
        });
    }
    //关闭双通道
    function disconnect(){
        if(stompClient != null) {
            stompClient.disconnect();
        }
        console.log("Disconnected");
    }
    function showResponse(message){
        var response = $("#name");
        response.append("<p>只有userID为"+message.id+"的人才能收到</p>");
    }
</script>
</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值