2016-10-07 72 views
1

我使用過的WebSocket 8080端口和angular2 4200端口angular2不能將消息發送到春天蹬過的WebSocket

@Configuration 
@EnableWebSocketMessageBroker 
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { 

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

    @Override 
    public void registerStompEndpoints(StompEndpointRegistry registry) { 
     registry.addEndpoint("/query/company/socket") 
     .setAllowedOrigins("*") 
     .withSockJS(); 
    } 

} 

春天和跺腳:

@MessageMapping("/hello") 
    @SendTo("/topic/greetings") 
    public Greeting greeting(HelloMessage message) throws Exception { 
     System.out.println(" start is : name is : "+message.getName()); 
     Thread.sleep(1000); // simulated delay 
     return new Greeting("Hello, " + message.getName() + "!"); 
    } 

和angular2:

import * as SockJS from 'sockjs-client'; 
const Stomp = require('stompjs/lib/stomp').Stomp; 
import {BehaviorSubject} from "rxjs"; 


    export class AppComponent implements OnInit{ 
     private host='http://localhost:8080'; 
     private url = `${this.host}/query/company/socket`; 
     private subUrl=`${this.host}/topic/greetings`; 
     private sendUrl=`${this.host}/app/hello`; 
     public stompClient: any; 

     ngOnInit(): void { 
     this.connect(); 
     } 

     connect() { 
     var that = this; 
     var socket = new SockJS(this.url); 
     this.stompClient = Stomp.over(socket); 
     this.stompClient.connect({}, function (frame) { 
      console.log('Connected: ' + frame); 
      that.stompClient.subscribe(this.subUrl, function (greeting) { 
      console.log(JSON.parse(greeting.body).content); 
      }); 
     }, function (err) { 
      console.log('err', err); 
     }); 
     } 

     public send() { 

     this.stompClient.send(this.sendUrl , {},  JSON.stringify({ 'name': 'jack' })); 

     } 
} 

運行時:鍍鉻控制檯---

Web Socket Opened... 
stomp.js:134 >>> CONNECT 
accept-version:1.1,1.0 
heart-beat:10000,10000 


stomp.js:134 <<< CONNECTED 
version:1.1 
heart-beat:0,0 


stomp.js:134 connected to server undefined 
app.component.ts:41 Connected: CONNECTED 
heart-beat:0,0 
version:1.1 


stomp.js:134 >>> SUBSCRIBE 
id:sub-0 
destination:undefined 

>>> SEND 
destination:http://localhost:8080/app/hello 
content-length:13 

{"name":"ll"} 

發送消息時:

彈簧控制檯:

WebSocketSession[1 current WS(1)-HttpStream(0)-HttpPoll(0), 1 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(1)-CONNECTED(1)-DISCONNECT(0)], stompBrokerRelay[null], inboundChannel[pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 9], outboundChannelpool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1], sockJsScheduler[pool size = 4, active threads = 1, queued tasks = 2, completed tasks = 441] 

發送從正面消息時,彈簧應該打印:

System.out.println(" start is : name is : "+message.getName()); 

但它不..

angular2沒有收到任何回覆..

+0

您需要添加'/ hello'作爲參數傳遞給'enableSimpleBroker()'以消息端點映射到控制器。 – drewmoore

+0

我嘗試添加'enableSimpleBroker(「/ topic」,「/ hello」);',但是spring沒有記錄來自angular2的接收消息...,它可能沒有問題,因爲 - I'@MessageMapping( 「/ hello」)'和'setApplicationDestinationPrefixes(「/ app」);'所以,我發送消息到'http:// localhost:8080/app/hello' .. –

+0

是的,你也需要這樣做或丟失前綴)。它與兩個工作? – drewmoore

回答

1

我已經解決了。

雖然我的angular2和彈簧使用不同的端口,4200,8080。

當我改變

private host='http://localhost:8080'; 
private subUrl=`${this.host}/topic/greetings`; 
private sendUrl=`${this.host}/app/hello`; 

private subUrl='/topic/greetings'; 
private sendUrl='/app/hello'; 

它工作正常,

,但我不知道原因。

+0

可能是由於CORS。您可能會從同一端口提供Angular和Server應用程序。所以'/ topic/greetings'實際上可以解析爲'protocol:// host:port // topic/greetings' – bhantol

0

我在運行在不同服務器上的兩個應用程序運行相同的問題。無論角我還註冊了客戶端的方式:

... 
var socket = new SockJS('http://localhost:8099/websocket'); 
... 
stompClient.subscribe('http://localhost:8099/ws/update', function (msg){ 
    console.log("received:", msg.body); 
}); 

隨着該綁定我沒有收到甚至我的瀏覽器插座工具列出的消息服務器的任何答案。 但由於某種原因,訂閱部分應該沒有主機。現在我的代碼如下所示:

... 
var socket = new SockJS('http://localhost:8099/websocket'); 
... 
stompClient.subscribe('/ws/update', function (msg){ 
    console.log("received:", msg.body); 
});