【发布时间】: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