2016-08-03 890 views
0

我正在設置兩個本地服務器之間的websocket以進行開發。WebSocket可以連接到本地服務器,但不能發送或接收

在一端我有http://localhost:8100/

運行我離子的應用程序在另一端我有一個春天的後端上http://localhost:9080/(或http://127.0.0.1:9080

連接運行已經建立,所以接下來我要用令牌發送消息給websocket(我知道這可以在SockJS 1.1.0中建立連接時發送,但我目前使用的是0.3.4)

但是,我在後端的代碼沒有' t似乎迴應,我想知道我的IP配置是否正確。我跟着一個教程,並在另一個項目中工作。

知道訂閱功能中的url是否需要以'localhost'或IP地址爲前綴的人有更多的經驗嗎?我知道websocket從http://更改爲ws://所以我想當這種情況發生時,我需要在它前面添加如下內容:ws:// localhost:9080/...

無論如何,這裏是我的代碼:

WebSocet服務:

function init() { 
     var socket = new SockJS('http://127.0.0.1:9080/ws-notification'); 
     stompClient = Stomp.over(socket); 
     stompClient.connect({}, function(frame) { 
      console.log('Connected: ' + frame); 
      /** 
      * Subscribe at /ws-topic/greetings url to catch messages 
      */ 
      stompClient.subscribe('/ws-topic/greetings', function(greeting){ 
       notify(JSON.parse(greeting.body).content); 
      }); 
      parseAuthentication(); 
     }); 
    } 

    function parseAuthentication(){ 
     stompClient.send("/ws-app/ws-notification",{},JSON.stringify({ 'token': authenticationService.isAuthenticated() })); 
    } 


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

    function notify(message){ 
     console.log("NOTIFY: "+message); 
    } 

WebSocket的配置:

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 


    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/ws-notification").setAllowedOrigins("*").withSockJS(); 
    } 

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

我Controllerfunction:

@MessageMapping("/ws-notification") 
@SendTo("/ws-topic/greetings") 
public Notify greeting(Notify notify) throws InterruptedException { 
    Thread.sleep(1000); 
    return new Notify("Hello, your token is :" + notify.getWsToken()); 
} 

請注意,當我在init()函數中設置連接時,我只指定了IP地址,試圖用ws://127.0.0.1作爲其他URL的前綴:但是沒有運氣!

回答

0

我找到了答案!

問題是我用來發送數據的模型中沒有默認的構造方法。

這也未實現或者在Spring WebSocket Tutorial

+0

提到能否請你解釋一下你是如何解決它exacly?我在該教程中看到的模型確實有默認的構造函數。對我來說,可以發送內容到春天,但我沒有得到任何東西在訂閱頻道。 –

+0

@JanWytze它可能是對象通知,它有一個字符串構造函數,所以如果他忘記聲明defalt構造函數,它將不存在,並且spring將失敗。 – Walfrat

相關問題