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



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

弹簧启动应用程序

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");
}
}

还有一个套接字文本处理程序类

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 安全性,则在 Spring 安全配置文件中允许此 URL。

最新更新