Spring Boot - Angular 5 Websocket

六月ゝ 毕业季﹏ 提交于 2020-01-06 06:03:14

问题


I am trying to implement Websockets in my SpringBoot - Angular 5 Application. I followed a tutorial. The source code provided in the tutorial works fine on my machine. But the same code is not working when I integrate it with the existing app.

Firefox throws the following error.

Firefox can’t establish a connection to the server at ws://localhost:5000/socket/658/k5z2si0f/websocket. vendor.8be84d89464cf9b74ba3.bundle.js:1:584796
Firefox can’t establish a connection to the server at http://localhost:5000/socket/658/c1cy4leo/eventsource.
vendor.8be84d89464cf9b74ba3.bundle.js:1:1681027
Load denied by X-Frame-Options: http://localhost:5000/socket/iframe.html#rxha50nq does not permit framing.
Load denied by X-Frame-Options: http://localhost:5000/socket/iframe.html#5og2ux3c does not permit framing.
Load denied by X-Frame-Options: http://localhost:5000/socket/658/chrqn1ly/htmlfile?c=_jp.ag1nuvt does not permit framing.
Load denied by X-Frame-Options: http://localhost:5000/socket/iframe.html#wonyug31 does not permit framing.
SyntaxError: expected expression, got '<'[Learn More] jsonp:1
Whoops! Lost connection to http://localhost:5000/socket vendor.8be84d89464cf9b74ba3.bundle.js:1:339486

SpringBoot throws the following error

2018-07-02 12:51:17.828  WARN 11260 --- [nio-5000-exec-6] o.s.web.servlet.PageNotFound             : Request method 'POST' not supported
2018-07-02 12:51:17.829  WARN 11260 --- [nio-5000-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
2018-07-02 12:51:17.894  WARN 11260 --- [nio-5000-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
2018-07-02 12:51:18.605  WARN 11260 --- [nio-5000-exec-7] o.s.web.servlet.PageNotFound             : Request method 'POST' not supported
2018-07-02 12:51:18.605  WARN 11260 --- [nio-5000-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported

Here is the front End Code

WebSocketService.ts

import { Injectable } from '@angular/core';
import SockJs from 'sockjs-client';
import Stomp from 'stompjs';
// const SockJs = require('sockjs-client');
// const Stomp = require('stompjs');
@Injectable()
export class WebSocketService {
  constructor() {
  }
  public connect() {
    const socket = new SockJs('/socket');
    const stompClient = Stomp.over(socket);
    return stompClient;
  }
}

WebSocketComponent.ts

import { HttpClient } from '@angular/common/http';
import { WebSocketService } from './../web-socket.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-web-socket',
  templateUrl: './web-socket.component.html',
  styleUrls: ['./web-socket.component.css']
})
export class WebSocketComponent implements OnInit {
  public notifications = 0;
  constructor(private websocketService: WebSocketService, private http: HttpClient) {
    const stompClient = this.websocketService.connect();
    stompClient.connect({}, frame => {

      // Subscribe to notification topic
      stompClient.subscribe('/topic/notification', notifications => {

        // Update notifications attribute with the recent messsage sent from the server
        this.notifications = JSON.parse(notifications.body).count;
      });
    });

  }

  getNotification() {
    this.http.get('/notify').subscribe(
      data => {
       console.log(data);
      }
    );
  }

  ngOnInit() {
  }

}

The Back end Code

WebSocketConfiguration.java

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

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

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

NotificationController.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class NotificationController {

    @Autowired
    private SimpMessagingTemplate template;

    // Initialize Notifications
    private Notifications notifications = new Notifications(0);

    @GetMapping("/notify")
    // @SendTo("/topic/notification")
    public Notifications getNotification() {
    System.out.println("Request received..");
    // Increment Notification by one
    notifications.increment();

    // Push notifications to front-end
    template.convertAndSend("/topic/notification", notifications);
    System.out.println("Response Sent..");
    return notifications;
    }
}

Notification.java

public class Notifications {

    private int count;

    public Notifications(int count) {
    this.count = count;
    }

    public int getCount() {
    return count;
    }

    public void setCount(int count) {
    this.count = count;
    }

    public void increment() {
    this.count++;
    }
}

application.properties

server.context-path : /

来源:https://stackoverflow.com/questions/51131269/spring-boot-angular-5-websocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!