java - Spring Boot - Angular 5 Websocket
问题描述
我正在尝试在我的 SpringBoot - Angular 5 应用程序中实现 Websockets。我跟着一个教程。本教程中提供的源代码在我的机器上运行良好。但是当我将它与现有应用程序集成时,相同的代码不起作用。
Firefox 抛出以下错误。
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 抛出如下错误
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
这是前端代码
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;
}
}
WebSocket组件.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() {
}
}
后端代码
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;
}
}
通知.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++;
}
}
应用程序属性
server.context 路径:/
解决方案
推荐阅读
- python - 将摄像头视频源上传到烧瓶休息 api
- html - 当我使用 findparent 和 findAll 抓取表格时的空列表
- windows-terminal - 如何使用更精细的默认字体大小
- csv - 是否可以将 Podio 报告导出为 csv/excel 文件?还是每天导出活动流?
- python - 逐帧打开nd2电影
- sql - 在 MySQL 上遇到错误代码 1111 我该如何解决?
- python - 将 Anaconda 重新安装到我的用户配置文件会修复我的权限错误吗?
- sql - ORACLE SQL将多行合并为一个并对字段求和
- java - ContextRefreshed 后 Spring WebApp 中 ScheduledFutureTask 中的 RejectedExecutionException
- c - C 中释放内存的递归解决方案