`
huangyongxing310
  • 浏览: 499106 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

SpringBootSpringSockJs 例子说明

阅读更多
SpringBootSpringSockJs 例子说明


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

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-websocket</artifactId>
	<version>${spring.version}</version>
</dependency>

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



后端代码:
package com.cesmart.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.annotation.SendToUser;
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 WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
	@Override
	public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
		// 在网页上可以通过"/applicationName/hello"来和服务器的WebSocket连接
		// ,如:http://localhost:8090/test
		// setAllowedOrigins("*")表示可以跨域
		// withSockJS()表示支持socktJS访问,在浏览器中使用
		stompEndpointRegistry.addEndpoint("/test").setAllowedOrigins("*").withSockJS();

	}

	@Override
	public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
		// 1.订阅模块定义,可以多个,如:"/topic","/uset"
		// 2.就是前端订阅了那个模块,当服务器要向那个模块发送信息时就从模块中取出对应的session,(session表明了是那个前端用户)
		// 3.就是那些前缀的URL可以
		messageBrokerRegistry.enableSimpleBroker("/topicTest", "/userTest"); // ,"/user"
		// 这句表示客户端向服务端发送时的主题上面需要加"/app"作为前缀,如:/app/hello
		messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
		// 1.这句表示给指定用户发送(一对一)的主题前缀,如“'/user/'+userid + '/otherMessage'”
		// 2.如果要使用@SendToUser,就不能设置这个,里面会自动实现一套方法,是在@SendToUser的URL前加“user+sessionId"组成
		messageBrokerRegistry.setUserDestinationPrefix("/userTest");
	}
}


package com.cesmart.controller;

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.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WebTest {

	@Autowired
	private SimpMessagingTemplate simpMessagingTemplate;

	// 表示服务端接收客户端通过主题“/app/hello”发送过来的消息(服务端接收消息接口)
	@MessageMapping("/hello")
	// 表示这个函数执行完成后会广播结果到"/topicTest/sayHello"这个主题,前端如果订阅了这个主题就会收到这个信息,
	// 相当于simpMessagingTemplate.convertAndSend("/topicTest/sayHello",
	// "sayHello");
	@SendTo("/topicTest/sayHello")
	public String greeting(String msg) throws Exception {
		System.out.println("greeting == " + msg);
		// simpMessagingTemplate.convertAndSend("/topicTest/sayHello",
		// "sayHello");
		msg = msg + "表示服务端接收客户端通过主题";
		return msg;
	}

	// 表示服务端接收客户端通过主题“/app/hello”发送过来的消息(服务端接收消息接口)
	@MessageMapping("/hello2")
	// 表示这个函数执行完成后会广播结果到"/topicTest/sayHello"这个主题,前端如果订阅了这个主题就会收到这个信息,
	// 相当于simpMessagingTemplate.convertAndSend("/topicTest/sayHello",
	// "sayHello");
	// @SendToUser("/topicTest/sayHello2/otherMessage")
	// 相当于simpMessagingTemplate.convertAndSendToUser(user, "/otherMessage", "
	// ==SendToUser推送给单一用户2==");
	public String greeting2(String msg) throws Exception {
		System.out.println("greeting2 == " + msg);
		String user = msg;
		simpMessagingTemplate.convertAndSendToUser(user, "/otherMessage", "==SendToUser推送给单一用户2==");

		return msg;
	}

	// 表示服务端接收客户端通过主题“/app/hello”发送过来的消息(服务端接收消息接口)
	@MessageMapping("/hello3")
	// 表示这个函数执行完成后会广播结果到"/topicTest/sayHello"这个主题,前端如果订阅了这个主题就会收到这个信息,
	// 相当于simpMessagingTemplate.convertAndSend("/topicTest/sayHello",
	// "sayHello");
	@SendToUser("/userTest/sayHello3")
	// 相当于simpMessagingTemplate.convertAndSendToUser(user, "/otherMessage", "
	// ==SendToUser推送给单一用户2==");
	public String greeting3(String msg) throws Exception {
		System.out.println("greeting3 == " + msg);
		String user = msg;
		msg = msg + " ==SendToUser推送给单一用户3==";
		return msg;
	}
}



package com.cesmart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan(basePackages = "com.cesmart") // 扫描那些包得到bean.@ComponentScan({"com.teradata.notification","com.teradata.dal"})
public class Application {
	public static void main(String[] args) {
		ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
	}
}



前端代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script src="http://121.43.38.142/webSocket/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="//cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
    <script src="//cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>

    <script type="text/javascript">
        function connect() {
            var socket = new SockJS('http://localhost:8090/test');
            var userid = document.getElementById('userId').value;
            stompClient = Stomp.over(socket);
            stompClient.connect('', '', function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topicTest/sayHello', function(message) {
                    console.log('message ==  ' + message.body);
                    //alert(message.body);
                });
                stompClient.subscribe('/userTest/'+userid + '/otherMessage', function(message) {
                    console.log('sayHello2 message  ==  ' + message.body);
                });
                stompClient.subscribe('/user/userTest/sayHello3', function(message) {
                    console.log('sayHello3 message  ==  ' + message.body);
                });
            });
        }

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

        function sendName() {
            console.log("sendName");
            var name = document.getElementById('message').value;
            stompClient.send("/app/hello", {}, "sendName");
            console.log("sendName2");
        }

        function sendName2() {
            console.log("sendName");
            var userid = document.getElementById('userId').value;
            var name = document.getElementById('message').value;
            stompClient.send("/app/hello2", {}, userid);
            console.log("sendName2");
        }
        function sendName3() {
            console.log("sendName");
            var userid = document.getElementById('userId').value;
            var name = document.getElementById('message').value;
            stompClient.send("/app/hello3", {}, userid);
            console.log("sendName3");
        }

    </script>
</head>
<body>
<div>
    <button id="connect" onclick="connect()">连接</button>
    <button id="disconnect" onclick="disconnect()">断开连接</button>
    <button id="send" onclick="sendName()">发送消息</button>
    <button id="send2" onclick="sendName2()">发送消息2</button>
    <button id="send3" onclick="sendName3()">发送消息3</button>
    <button id="reconnect" onclick="reconnect()">重新连接</button>
</div>
<div>
    <textarea id="message" style="width: 350px">Here is a message!</textarea>
</div>
<div>
    <textarea id="userId" style="width: 350px">123456789</textarea>
</div>
<div>日志信息:</div>
<p id="console" width="600px"></p>
</body>
</html>



参考(spring websocket 使用@SendToUser):http://blog.csdn.net/yingxiake/article/details/51224569
参考(Spring WebSocket教程):http://www.tuicool.com/articles/EFJvya
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics