spring boot rest 和 angular2 with websocket (stomp over sockjs)

spring boot rest and angular2 with websocket (stomp over sockjs)

是否可以在没有 MVC 的情况下使用 stomp 而不是 sockjs。所以我想在 tomcat 中有 spring rest 接口,通过 express.

有 angular2 应用程序 运行

WebSocketConfig.java

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // the endpoint for websocket connections
        registry.addEndpoint("/portfolio").setAllowedOrigins("*").withSockJS();
    }

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

SocketController.java

@Controller
public class SocketController {

    @Autowired
    private SimpMessagingTemplate template;

    public SocketController() {
        int a = 5;
    }

    @MessageMapping("/greeting")
    public String handle(String greeting) {
        return "[" + "greeting" + ": " + greeting;
    }
}

和打字稿代码:

。 . .

constructor() {

        var socket = new SockJS('http://localhost:8080/portfolio');
        this.stompClient = Stomp.over(socket);
        this.stompClient.connect("guest", "guest", function(frame) {
            console.log('Connected: ' + frame);
            this.stompClient.subscribe('http://localhost:8080/topic/greeting', function(greeting) {
                console.log("from from", greeting);
            });
        }, function (err) {
            console.log('err', err);
        });
    }

。 . .

send() {
    this.stompClient.send("http://localhost:8080/app/greeting", {}, JSON.stringify({ 'name': "kitica" }));
}

。 . .

但由于某种原因这不起作用..在控制台中我得到输出:

Opening Web Socket...
stomp.js:134 Web Socket Opened...
stomp.js:134 >>> CONNECT
login:guest
passcode:guest
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
activity-socket.ts:17 Connected: CONNECTED
heart-beat:0,0
version:1.1

当我发送时我得到

>>> SEND
destination:http://localhost:8080/app/greeting
content-length:17

{"name":"kitica"}

但消息永远不会返回给订阅者。

angular2 在端口 8001 上 spring 其余在 8080

我自己在使用 angular2 客户端时遇到了一些问题,使用 stomp over SockJs 与 Java spring-boot 后端。这是我为使其工作所做的工作:

angular 方:

this.stompClient.subscribe cannot be find, so bind "this" to "that".

constructor() {
    var that = this;
    var socket = new SockJS('http://localhost:8080/portfolio');
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect("guest", "guest", function(frame) {
        console.log('Connected: ' + frame);
        that.stompClient.subscribe('http://localhost:8080/topic/greeting', function(greeting) {
            console.log("from from", greeting);
        });
    }, function (err) {
        console.log('err', err);
    });
}

在 Java 服务器端:

Your Controller need an annotation that said where the vallue is returned like this:

@MessageMapping("/greeting")
@SendTo("/topic/greetings")
public String handle(String greeting) {
    return "[" + "greeting" + ": " + greeting;
}

根据您的消息代理。

希望对您有所帮助。

令人困惑的部分是我正在使用 spring-boot-rest 并且我没有将 angular2 作为来自 tomcat 容器的静态服务,我在 webpack 下有 angular2 所以我一直在尝试订阅并发送给亲戚 URL.

正确的做法是:

import {Component} from '@angular/core';
import {ActivityService} from '../common/services';
import {MaterializeDirective} from 'angular2-materialize';
import {LarsActionButtonComponent} from '../common/components';

var SockJS = require('sockjs-client');
var Stomp = require('stompjs');

@Component({
selector: 'activity',
providers: [ActivityService],
directives: [MaterializeDirective, LarsActionButtonComponent],
templateUrl: 'app/activity/activity.html'
})

export class Activity {
stompClient: any;

activityId: any;
text: any;
messages: Array<String> = new Array<String>();

constructor() {
}

send() {
    this.stompClient.send('/app/hello/' + this.activityId, {},      JSON.stringify({ 'name': this.text }));
}

connect() {
    var that = this;
    var socket = new SockJS('tst-rest.mypageexample/hello?activityId=' + this.activityId);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        that.stompClient.subscribe('/topic/greetings/' + that.activityId, function (greeting) {
            that.messages.push(JSON.parse(greeting.body).content);
        });
    }, function (err) {
        console.log('err', err);
    });
}

}

并在 spring 控制器中:

@Controller
public class SocketController {


@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
    return new Greeting("Hello, " + message.getName() + "!");
}

}

配置class:

@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("/hello").setAllowedOrigins("*").withSockJS();
    }

}

您已将 'handle()' 方法值发送给订阅者 要么使用 simpMessagingTemplate.convertAndSend(, ); 例如- simpMessagingTemplate.convertAndSend("/topic/chats", message.getMessage());

或 @SendTo("destination url") 在处理程序方法之上。 例如- @SendTo("/topic/message")