import * as SockJS from 'sockjs-client';
public stompClient: any;
const Stomp = require('stompjs/lib/stomp').Stomp;
ngOnInit() {
this.connect();
}
connect() {
const socket=new SockJS(sockUrl);
this.stompClient=Stomp.over(socket);
this.stompClient.connect({},e=>{
this.connected=true;
console.log('Connected: ' + e);
this.stompClient.subscribe(this.subUrl,v=>{
console.log(JSON.parse(v.body).content);
this.mm.next(JSON.parse(v.body).content);
})
})
}
public send() {
this.stompClient.send(this.sendUrl,{},JSON.stringify({ 'name': value }));
}
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// client 链接的 socket url
registry.addEndpoint("/socket")
.setAllowedOrigins("http://localhost:8080")
.withSockJS()
;
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
}
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting g(HelloMessage message) throws InterruptedException {
log.info("stock web is start ! from is : " + message);
TimeUnit.SECONDS.sleep(1); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
the socket can opening .