gpt4 book ai didi

java - 无法通过 Chrome 扩展连接到使用 Spring 创建的简单 websocket 服务器

转载 作者:行者123 更新时间:2023-12-05 07:14:38 26 4
gpt4 key购买 nike

这是在 Spring 上创建的 WebSocket 服务器的三个简单组件

Spring Boot 应用:

package test.andrew;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Websocket 服务器配置文件:

package test.andrew;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new SocketTextHandler(), "/name");
}

}

和一个 Socket 文本处理程序类:

package test.andrew;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Component
public class SocketTextHandler extends TextWebSocketHandler {

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {

session.sendMessage(new TextMessage("Pong"));
}

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
session.sendMessage(new TextMessage("Connection established"));
}
}

我的问题是服务器无法正常工作,例如,当使用普通的旧 javax.websocket 时我无法通过智能 Websocket 客户端 Chrome 扩展建立连接,因此无法继续向 wss 发送消息。

如果您能提供帮助或建议,我将不胜感激!

最佳答案

我通过修改 WebSocketConfig 类来解决这个问题:

package test.andrew;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;


@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new SocketTextHandler(), "/name").setAllowedOrigins("*");
}
}

请注意调用了 .setAllowedOrigins("*") 方法。允许来源后,我们可以通过 chrome 扩展程序调用此 web 套接字 url。

如果您使用的是 spring security,则在 spring security 配置文件中允许此 url。

关于java - 无法通过 Chrome 扩展连接到使用 Spring 创建的简单 websocket 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com