欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot WebSocket stomp简单例子

程序员文章站 2022-04-09 13:37:09
...

pom.xml

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

StompApplication.java

package stomp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class})
public class StompApplication {
	public static void main(String[] args) {
		SpringApplication.run(StompApplication.class, args);
	}
}

WebSocketConfiguration.java

package stomp;

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;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/stompwebsocket").withSockJS();
	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		config.enableSimpleBroker("/queue/", "/topic/");
		config.setApplicationDestinationPrefixes("/app");
	}

}

MyController.java

package stomp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class MyController {
	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;

	@MessageMapping("/send.message")
	public void sendPublicMessage(String msg) {
		simpMessagingTemplate.convertAndSend("/topic/public.messages", msg);
	}
}

stomp.html

<html>
<script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>  
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>  
<script type="text/javascript">
var socket = new SockJS('/stompwebsocket');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
	stompClient.subscribe('/topic/public.messages', function(txt) {
		alert(txt);
	});
});

function send(txt) {
	stompClient.send("/app/send.message", {}, txt);
}
</script>
<button onclick="send(new Date())">Send</button>
</html>

运行,然后打开两个浏览器,访问http://127.0.0.1:8080/stomp.html, 点击一个页面的Send,消息会广播道其他窗口。