码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot---Web开发---WebSocket

时间:2019-01-12 15:56:42      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:tomcat   分享   show   document   project   服务器   tom   points   ada   

【广播式】

1、

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.an</groupId>
    <artifactId>springbootwebsocket</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootwebsocket</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

技术分享图片

2、application.properties

#Tomcat
server.tomcat.uri-encoding=utf-8
server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=100
server.port=8080
server.servlet.context-path=/


#Thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.servlet.content-type=text/html


spring.resources.static-locations=classpath:/static/

3、ws.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot+WebSocket【广播模式】</title>
</head>
<body onload="disconnect();">
<noscript>
    <h2>您的浏览器不支持WebSocket!</h2>
</noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    </div>
    <div id="conversationDiv">
        <label>输入你的名字</label><input type="text" id="name"/>
        <button id="sendName" onclick="sendName();">发送</button>
        <p id="response"></p>
    </div>
</div>
<script th:src="@{stomp.js}"></script>
<script th:src="@{sockjs.js}"></script>
<script th:src="@{jquery.min.js}"></script>
<script type="text/javascript">
    var stompClient=null;
    
    function setConnected(connected) {
        document.getElementById("connect").disabled=connected;
        document.getElementById("disconnect").disabled=!connected;
        document.getElementById("conversationDiv").style.visibility=connected?visible:hidden;
        $("#response").html();
    }

    function connect() {
        var socket=new SockJS("/endpointWisely");
        stompClient=Stomp.over(socket);
        stompClient.connect({},function (frame) {
            setConnected(true);
            console.log(Connected+frame);
            //通过stompClient.subscribe订阅   /topic/getResponse目标(在Controller的@SendTo中定义)  发送的消息
            stompClient.subscribe(/topic/getResponse,function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }

    function disconnect() {
        if (stompClient!=null){
            stompClient.disconnect();
        }
        setConnected(false);
        console.log(DisConnected);
    }

    function sendName() {
        var name=$("#name").val();
        //通过stompClient.send向  /welcome目标(在Controller的@MessageMapping中定义)  发送消息
        stompClient.send("/welcome",{},JSON.stringify({name:name}));
    }

    function showResponse(message) {
        var response=$("#response");
        response.html(message);
    }
</script>
</body>
</html>

4、

package com.an.springbootwebsocket;

/**
 * 浏览器向服务器发送消息,用此类接受
 */
public class WiselyMessage {

    private String name;

    public String getName() {
        return name;
    }
}

5、

package com.an.springbootwebsocket;

/**
 * 服务器向浏览器发送的消息
 */
public class WiselyResponse {

    private String responseMessage;

    public WiselyResponse(String responseMessage){
        this.responseMessage=responseMessage;
    }

    public String getResponseMessage() {
        return responseMessage;
    }
}

6、

package com.an.springbootwebsocket;

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;

/**
 * 通过@EnableWebSocketMessageBroker开启使用STOMP协议来传输基于代理的消息;
 * Controller使用@MessageMapping,类似于@RequestMapping
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    /**
     * 注册STOMP协议的节点,并映射指定的URL
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //注册一个STOMP协议的endpoint,并指定使用SockJS协议
        registry.addEndpoint("/endpointWisely").withSockJS();
    }

    /**
     * 配置消息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //广播式应配置一个/topic消息代理
        registry.enableSimpleBroker("/topic");
    }
}

7、

package com.an.springbootwebsocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ws").setViewName("/ws");
    }
}

8、

package com.an.springbootwebsocket;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class WsController {


    /**
     * 1、当浏览器向服务器发送请求时,通过@MessageMapping映射/welcome地址;
     * 2、当服务器有消息时,会对订阅了@SendTo中的路径的浏览器发送消息
     * @param wiselyMessage
     * @return
     */
    @MessageMapping(value = "/welcome")
    @SendTo(value = "/topic/getResponse")
    public WiselyResponse say(WiselyMessage wiselyMessage){
        return new WiselyResponse(wiselyMessage.getName());
    }
}

 

SpringBoot---Web开发---WebSocket

标签:tomcat   分享   show   document   project   服务器   tom   points   ada   

原文地址:https://www.cnblogs.com/anpeiyong/p/10259927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!