You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular客户端与Spring Boot服务器WebSocket连接失败求助

解决Angular + Stomp.js连接Spring Boot WebSocket的报错问题

问题描述

尝试通过Sock.js和Stomp.js实现Angular客户端与Spring Boot服务器的WebSocket连接时,浏览器出现如下报错:

WebSocket连接报错

服务端Spring Boot配置代码

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws-endpoint").setAllowedOrigins("http://localhost:4200").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic"); // 启用内存消息代理
        registry.setApplicationDestinationPrefixes("/app"); // 控制器接收消息的前缀
    }
}

客户端Angular代码

import { Injectable } from '@angular/core';
import {Client, Message} from "@stomp/stompjs";

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {

  public client: Client;

  constructor() {
    this.client = new Client({
      brokerURL: 'ws://localhost:8080/ws-endpoint',
      debug: (msg: string) => {
        console.log(msg);
      }
    });
  }

  connect() {
    this.client.activate();
  }

  subscribe(destination: string, callback: (message: Message) => void) {
    this.client.subscribe(destination, callback);
  }

  sendMessage(destination: string, message: string) {
    this.client.publish({ destination, body: message });
  }
}

解决方案

报错核心原因:服务端启用了SockJS支持,但客户端直接使用原生WebSocket协议(ws://)连接,未适配SockJS的握手流程。按以下步骤修改客户端代码:

  1. 安装SockJS客户端依赖
    在Angular项目根目录执行:
npm install sockjs-client
  1. 修改WebSocket服务配置
    导入SockJS并配置webSocketFactory替代brokerURL:
import { Injectable } from '@angular/core';
import {Client, Message} from "@stomp/stompjs";
import * as SockJS from 'sockjs-client';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {

  public client: Client;

  constructor() {
    this.client = new Client({
      // 使用SockJS创建连接,适配服务端的SockJS配置
      webSocketFactory: () => new SockJS('http://localhost:8080/ws-endpoint'),
      debug: (msg: string) => {
        console.log(msg);
      }
    });
  }

  connect() {
    this.client.activate();
  }

  subscribe(destination: string, callback: (message: Message) => void) {
    this.client.subscribe(destination, callback);
  }

  sendMessage(destination: string, message: string) {
    this.client.publish({ destination, body: message });
  }
}
  1. 额外检查项
  • 确认Spring Boot应用已添加spring-boot-starter-websocket依赖
  • 验证Angular运行端口(4200)与服务端setAllowedOrigins配置一致
  • 确保服务端正常运行在8080端口,无端口冲突

内容的提问来源于stack exchange,提问作者Ostap Melnychuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 01:43:42