springboot+websocket+stomp+sockjs+rabbitmq實現消息推送或即時通訊

總結一下實現過的springboot+websocket+stomp+sockjs+rabbitmq的問題
如何實現,網上的代碼非常多,很容易就實現,具體的理解要看自己了,websocket本身是支持
文本和二進制傳輸,但是sockJS是不支持二進制的,經過查詢了一下,作者也說沒有時間搞這一塊,lz自己測試客戶端到服務端是可以傳輸二進制的,但是服務器無法向web端傳輸二進制,發送二進制會斷開websocket連接。所以如果需要傳輸二進制,可以直接使用websocket。sockjs的優勢在於可以處理不支持websocket的瀏覽器,會使用輪訓來實現

使用的是springboot2.1.7
pom.xml添加依賴

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

java類


import java.security.Principal;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.converter.ByteArrayMessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

@Configuration
@EnableWebSocketMessageBroker // 註解開啓STOMP協議來傳輸基於代理的消息,此時控制器支持使用@MessageMapping
public class WebSocketConfig  implements WebSocketMessageBrokerConfigurer {

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		config.enableSimpleBroker("/topic", "/user");// topic用來廣播,user用來實現p2p
	}
	
	@Override
	public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
		messageConverters.add(new ByteArrayMessageConverter());
        return true;
    }

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/webServer").setHandshakeHandler(new DefaultHandshakeHandler() {
			@Override
			protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
					Map<String, Object> attributes) {
				// 將客戶端標識封裝爲Principal對象,從而讓服務端能通過getName()方法找到指定客戶端
				Object o = attributes.get("name");
				return new FastPrincipal(o.toString());
			}
		}).addInterceptors(new HandleShakeInterceptors()).setAllowedOrigins("*");//.withSockJS()
		registry.addEndpoint("/queueServer").setHandshakeHandler(new DefaultHandshakeHandler() {
			@Override
			protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
					Map<String, Object> attributes) {
				// 將客戶端標識封裝爲Principal對象,從而讓服務端能通過getName()方法找到指定客戶端
				Object o = attributes.get("name");
				return new FastPrincipal(o.toString());
			}
		}).addInterceptors(new HandleShakeInterceptors()).setAllowedOrigins("*");//.withSockJS() 註冊兩個STOMP的endpoint,分別用於廣播和點對點
	}
	
	/**
	 * 這是用於配置服務器向瀏覽器發送的消息。 clientOut就表示出出口。還有一個inBoundChannel用於處理瀏覽器向服務器發送的消息
	 * corePoolSize(1)處理的工作線程設置1,阻塞保證消息時序性,期待更好的解決方案(比如多個消費者動態創建多個queue)
	 * 
	 * @param registration
	 */
	@Override
	public void configureClientOutboundChannel(ChannelRegistration registration) {
		registration.taskExecutor().corePoolSize(1).maxPoolSize(1);
	}

	// 定義一個自己的權限驗證類
	class FastPrincipal implements Principal {

		private final String name;

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

		public String getName() {
			return name;
		}
	}
	
}

HandleShakeInterceptors.java


import java.util.Map;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

/**
 * 檢查握手請求和響應, 對WebSocketHandler傳遞屬性
 */
public class HandleShakeInterceptors implements HandshakeInterceptor {

    /**
     * 在握手之前執行該方法, 繼續握手返回true, 中斷握手返回false.
     * 通過attributes參數設置WebSocketSession的屬性
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String name= ((ServletServerHttpRequest) request).getServletRequest().getParameter("name");
        //保存客戶端標識
        attributes.put("name", "caopc");
        return true;
    }

    /**
     * 在握手之後執行該方法. 無論是否握手成功都指明瞭響應狀態碼和相應頭.
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception exception) {

    }
    
}

web端訪問的controller

@Controller
public class SubController {

	
    @Autowired
    public SimpMessagingTemplate template;  
      
    
    @MessageMapping("/subscribe")
    public void subscribe(ReceiveMessage rm) {
        for(int i =1;i<=20;i++) {
            //廣播使用convertAndSend方法,第一個參數爲目的地,和js中訂閱的目的地要一致
            template.convertAndSend("/topic/getResponse", rm.getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    
    @MessageMapping("/queue")
    //public void queue(ReceiveMessage rm) {
    	 public void queue(Principal principal,Message<byte[]> message) throws UnsupportedEncodingException {
            /*廣播使用convertAndSendToUser方法,第一個參數爲用戶id,此時js中的訂閱地址爲
            "/user/" + 用戶Id + "/message",其中"/user"是固定的*/
	    	byte[]  messageInByte = message.getPayload();
	    	System.out.println(new String(messageInByte,"utf-8"));
    		//parseMessage(new String(messageInByte,"utf-8"));
    		template.convertAndSendToUser("userid","/message",messageInByte);
    		

    }

然後是queue.html,轉換方法可以不用在意,是lz測試時候使用的

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello queue</title>
    <script src="sockjs.min.js"></script>
    <script src="stomp.js"></script>
    <script src="jquery-3.2.1.min.js"></script>   
    <script type="text/javascript">
        var stompClient = null;
        var stompClientReceive = null;
        function setConnected(connected){
            document.getElementById("connect").disabled = connected;
            document.getElementById("disconnect").disabled = !connected;
            $("#response").html();
        }
        function connect() {
        	var url = "http://localhost:8989/stomp";
        	//var client = Stomp.client(url);
            //var socket = new SockJS("/queueServer");
            //socket.binaryType = "arraybuffer";
            //stompClient = Stomp.over(socket);
            stompClient = Stomp.client('ws://192.168.1.50:8989/queueServer');
            stompClient.binaryType = "arraybuffer";
            //stompClient.connect({userid:userid},function(frame)
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/user/'+document.getElementById('user').value+'/message', function(response){
                	var response1 = document.getElementById('response');
                	var bytes = new Array();
                	bytes = response.body;
                	console.log(bytes);
                    console.log("return");
                    var p = document.createElement('p');
                    p.style.wordWrap = 'break-word';
                    p.appendChild(document.createTextNode(response.body));
                    response1.appendChild(p);
                });
            });
            var socketReceive = new SockJS("/queueServer");
            //socketReceive.binaryType = "arraybuffer";
            //stompClientReceive = Stomp.over(socketReceive);
            stompClientReceive = Stomp.client('ws://xx.xxx.xxx.xx:8989/queueServer');
            stompClientReceive.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClientReceive.subscribe('/user/'+document.getElementById('user').value+'/wavmessage', function(response){
                	console.log(response);
                	console.log(response.body);
                	sendFileInfo(response.body);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }
        
        function sendFileInfo(mes) {
            stompClient.send("/queue", {}, JSON.stringify({ 'name': mes,'type': 'message','deviceId': '','userId': ''}));
        }
        
        function sendName() {
            var name = document.getElementById('name').value;
            //stompClient.send("/queue", {}, JSON.stringify({ 'name': name,'type': 'control','deviceId': '','userId': document.getElementById('user').value}));
            //var str   = '000000';
            //將字符串轉換爲byte數組
            //var str = JSON.stringify({ 'name': name,'type': 'control','deviceId': '','userId': ''})
    		
            var loginStr = JSON.stringify({ 'head': {'cmd': 'web_login','token':'231231231',"client_type": "web", 'user_id': ''}});
            var logoutStr = JSON.stringify({ 'head': {'cmd': 'web_logout','token':'231231231',"client_type": "web", 'user_id': ''}});
            var stopAudioStr = JSON.stringify({ 'head': {'cmd': 'stop_data','token':'231231231',"device_id": "設備ID", 'user_id': ''}});
            
            var str   = '111111';
			//var bytes = strToByte(str);
			//stompClient.send("/queue", {}, str);
			//console.log(bytes);
			//console.log(bytes.length);
			//stompClient.send("/queue", {}, stopAudioStr);
			
			var bytesArr= stringToByte(str);   
			var bytes =new Uint8Array(bytesArr.length) ;
			for (var i = 0; i < bytes.length; i++) {
				bytes[i]=bytesArr[i];
			}  
			console.log(bytes)
			console.log(encode(bytes));
			var headers = {
					'content-type': 'application/octet-stream'
				};
            stompClient.send("/queue", headers, bytes);
           // stompClient.send("/queue", {}, strToArr(name));
            
          
        }
        
        function strToByte(str) {  

            var ch, st, re = []; 
            for (var i = 0; i < str.length; i++ ) { 
                ch = str.charCodeAt(i);  // get char  
                st = [];                 // set up "stack"  

               do {  
                    st.push( ch & 0xFF );  // push byte to stack  
                    ch = ch >> 8;          // shift value down by 1 byte  
                }    

                while ( ch );  
                // add stack contents to result  
                // done because chars have "wrong" endianness  
                re = re.concat( st.reverse() ); 
            }  
            // return an array of bytes  
            return re;  
        } 
        
        
        
      //將字符串轉爲 Array byte數組
		function stringToByte(str) {  
			    var bytes = new Array();  
			    var len, c;  
			    len = str.length;  
			    for(var i = 0; i < len; i++) {  
			        c = str.charCodeAt(i);  
			        if(c >= 0x010000 && c <= 0x10FFFF) {  
			            bytes.push(((c >> 18) & 0x07) | 0xF0);  
			            bytes.push(((c >> 12) & 0x3F) | 0x80);  
			            bytes.push(((c >> 6) & 0x3F) | 0x80);  
			            bytes.push((c & 0x3F) | 0x80);  
			        } else if(c >= 0x000800 && c <= 0x00FFFF) {  
			            bytes.push(((c >> 12) & 0x0F) | 0xE0);  
			            bytes.push(((c >> 6) & 0x3F) | 0x80);  
			            bytes.push((c & 0x3F) | 0x80);  
			        } else if(c >= 0x000080 && c <= 0x0007FF) {  
			            bytes.push(((c >> 6) & 0x1F) | 0xC0);  
			            bytes.push((c & 0x3F) | 0x80);  
			        } else {  
			            bytes.push(c & 0xFF);  
			        }  
			    }  
			    return bytes;  
	
	
			}
      
		// private property
		  var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    
		 function encode (input) {
		      var output = "";
		      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		      var i = 0;
		      input = _utf8_encode(input);
		      while (i < input.length) {
		          chr1 = input.charCodeAt(i++);
		          chr2 = input.charCodeAt(i++);
		          chr3 = input.charCodeAt(i++);
		          enc1 = chr1 >> 2;
		          enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		          enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		          enc4 = chr3 & 63;
		          if (isNaN(chr2)) {
		              enc3 = enc4 = 64;
		          } else if (isNaN(chr3)) {
		              enc4 = 64;
		          }
		          output = output +
		              _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
		              _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		      }
		      return output;
		  }

		  // public method for decoding
		  function decode(input) {
		      var output = "";
		      var chr1, chr2, chr3;
		      var enc1, enc2, enc3, enc4;
		      var i = 0;
		      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		      while (i < input.length) {
		          enc1 = _keyStr.indexOf(input.charAt(i++));
		          enc2 = _keyStr.indexOf(input.charAt(i++));
		          enc3 = _keyStr.indexOf(input.charAt(i++));
		          enc4 = _keyStr.indexOf(input.charAt(i++));
		          chr1 = (enc1 << 2) | (enc2 >> 4);
		          chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		          chr3 = ((enc3 & 3) << 6) | enc4;
		          output = output + String.fromCharCode(chr1);
		          if (enc3 != 64) {
		              output = output + String.fromCharCode(chr2);
		          }
		          if (enc4 != 64) {
		              output = output + String.fromCharCode(chr3);
		          }
		      }
		      output = _utf8_decode(output);
		      return output;
		  }
		  
		// private method for UTF-8 encoding
		  _utf8_encode = function (string) {
		      string = string.toString().replace(/\r\n/g,"\n");
		      var utftext = "";
		      for (var n = 0; n < string.length; n++) {
		          var c = string.charCodeAt(n);
		          if (c < 128) {
		              utftext += String.fromCharCode(c);
		          } else if((c > 127) && (c < 2048)) {
		              utftext += String.fromCharCode((c >> 6) | 192);
		              utftext += String.fromCharCode((c & 63) | 128);
		          } else {
		              utftext += String.fromCharCode((c >> 12) | 224);
		              utftext += String.fromCharCode(((c >> 6) & 63) | 128);
		              utftext += String.fromCharCode((c & 63) | 128);
		          }

		      }
		      return utftext;
		  }

		  // private method for UTF-8 decoding
		  _utf8_decode = function (utftext) {
		      var string = "";
		      var i = 0;
		      var c = c1 = c2 = 0;
		      while ( i < utftext.length ) {
		          c = utftext.charCodeAt(i);
		          if (c < 128) {
		              string += String.fromCharCode(c);
		              i++;
		          } else if((c > 191) && (c < 224)) {
		              c2 = utftext.charCodeAt(i+1);
		              string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
		              i += 2;
		          } else {
		              c2 = utftext.charCodeAt(i+1);
		              c3 = utftext.charCodeAt(i+2);
		              string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
		              i += 3;
		          }
		      }
		      return string;
		  }
      
      
		
    </script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div>
        <labal>用戶Id</labal><input type="text" id="user" />
        <button id="connect" onclick="connect();">Connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
        <labal>控制消息</labal><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>

</body>
</html>

topic.html

<html>
<head>
    <meta charset="UTF-8">
    <title>Hello topic</title>
    <script src="sockjs.min.js"></script>
    <script src="stomp.js"></script>
    <script src="jquery-3.2.1.min.js"></script>   
    <script type="text/javascript">
        var stompClient = null;
        function setConnected(connected){
            document.getElementById("connect").disabled = connected;
            document.getElementById("disconnect").disabled = !connected;
            $("#response").html();
        }
        function connect() {
            var socket = new SockJS("/webServer");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/getResponse', function(response){
                    var response1 = document.getElementById('response');
                    var p = document.createElement('p');
                    p.style.wordWrap = 'break-word';
                    p.appendChild(document.createTextNode(response.body));
                    response1.appendChild(p);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }
        
        function sendName() {
            var name = document.getElementById('name').value;
            console.info(1111111111);
            stompClient.send("/subscribe", {}, JSON.stringify({ 'name': name }));
        }
    </script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">Connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
        <labal>UserId</labal><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>

</body>
</html>

application配置文件只配置rabbitmq地址即可

server.port=8989
spring.application.name=xxxx
#spring.rabbitmq.host= 40.122.118.224
#spring.rabbitmq.port= 5672
#spring.rabbitmq.username=xxx
#spring.rabbitmq.password=xxxx
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章