springboot整合websocket

参考链接:https://spring.io/guides/gs/messaging-stomp-websocket/

使用Maven构建项目pom文件参考, 其它工具构建方式类似, 具体参考官网


        org.springframework.boot
        spring-boot-starter-parent
        2.0.5.RELEASE
    

    
        
            org.springframework.boot
            spring-boot-starter-websocket
        

        
            org.webjars
            webjars-locator-core
        
        
            org.webjars
            sockjs-client
            1.0.2
        
        
            org.webjars
            stomp-websocket
            2.3.3
        
        
            org.webjars
            bootstrap
            3.3.7
        
        
            org.webjars
            jquery
            3.1.0
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        1.8
    

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

创建两个java实体类

public class HelloMessage {

    private String name;

    public HelloMessage() {
    }

    public HelloMessage(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Greeting {
    private String content;

    public Greeting() {
    }

    public Greeting(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

新建controller文件

@Controller
public class GreetingController {


    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(1000); // simulated delay
        return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
    }

}

新建配置文件

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 配置消息代理(中介)
     * enableSimpleBroker 服务端推送给客户端的路径前缀
     * setApplicationDestinationPrefixes  客户端发送数据给服务器端的一个前缀
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    /**
     * 注册端点,发布或者订阅消息的时候需要连接此端点
     * setAllowedOrigins 非必须,*表示允许其他域进行连接
     * withSockJS  表示开始sockejs支持
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gs-guide-websocket").withSockJS();
    }

}

在src/main/resources/static/ 目录新建index.html




    Hello WebSocket
    
    
    
    
    
    



Greetings

在src/main/resources/static/ 目录新建app.js文件

var stompClient = null;

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    var socket = new SockJS('/gs-guide-websocket'); //连接上端点(基站)
    stompClient = Stomp.over(socket); //用stom进行包装,规范协议
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}

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

function sendName() {
    stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
}

function showGreeting(message) {
    $("#greetings").append("" + message + "");
}

$(function () {
    $("form").on('submit', function (e) {
        e.preventDefault();
    });
    $( "#connect" ).click(function() { connect(); });
    $( "#disconnect" ).click(function() { disconnect(); });
    $( "#send" ).click(function() { sendName(); });
});

启动项目后, 后台分别开两个圈口访问:localhost:8080/
springboot整合websocket_第1张图片

你可能感兴趣的:(websocket)