【问题标题】:spring boot rest and angular2 with websocket (stomp over sockjs)带有websocket的弹簧靴休息和angular2(踩过sockjs)
【发布时间】:2016-07-14 07:46:09
【问题描述】:

是否可以在没有 MVC 的情况下在 sockjs 上使用 stomp。所以我想在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 上,弹簧座在 8080 上

【问题讨论】:

  • 如果你可以在JS中使用它,你可以在Angular2中使用它。
  • 我已经用我尝试过的代码示例更新了问题,这是根据他们的文档
  • 请问您是如何在您的 angular2 应用程序中添加 sockJS 的?
  • 如果您的问题更具体,我可以给出更合适的答案。但它是非常简单的 npm 安装,稍后在你的 typescript 文件中你必须声明变量 SockJS 和 Stomp。我希望它是有帮助的。编辑:参考stackoverflow.com/a/37094682/2662587

标签: spring tomcat angular stomp sockjs


【解决方案1】:

令人困惑的部分是我使用的是 spring-boot-rest 并且我没有从 tomcat 容器中将 angular2 作为静态服务,我在 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);
    });
}

}

在弹簧控制器中:

@Controller
public class SocketController {


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

}

配置类:

@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();
    }

}

【讨论】:

  • 你使用什么 npm 库?只需“npm install stomp”就足够了
  • 请看我上面的回答,刚刚更新了
  • 你是如何在 webpack 中映射 sockjs-client 的?
  • 我在 package.json 中只有 "sockjs": "0.3.4", "stompjs": "2.3.3",其他的都显示出来了。
  • @critical 如果我失去与套接字的连接,如何自动重新连接?
【解决方案2】:

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

在角度方面:

找不到this.stompClient.subscribe,所以将“this”绑定到“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 服务器端:

您的控制器需要一个注释,说明返回值的位置,如下所示:

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

根据您的消息代理。

希望对您有所帮助。

【讨论】:

  • 如果我失去与套接字的连接,如何自动重新连接?
  • @Lanou 非常感谢,它解决了我的问题!
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2018-07-22
    • 2018-02-14
    • 2017-08-23
    • 2015-05-25
    • 2020-03-12
    • 2014-03-09
    • 1970-01-01
    • 2014-06-27
    相关资源
    最近更新 更多