JavaScript客户端无法连接到spring4 WebSocket



我在spring中实现了websocket,但是JavaScript客户端无法连接到websocket。

下面是WebSocketConfig类:
package com.myapp.spring.security.config;
import com.myapp.spring.web.controller.MyWebSocketHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.PerConnectionWebSocketHandler;
@Configuration
@EnableWebMvc
@EnableWebSocket
@ComponentScan(basePackages={"com.myapp.spring.*"})
public class WebSocketConfig implements WebSocketConfigurer {
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                .addHandler(myWebSocketHandler(), "/endpoint")
                .setAllowedOrigins("*");
    }
    @Bean
    public WebSocketHandler myWebSocketHandler() {
        return new PerConnectionWebSocketHandler(MyWebSocketHandler.class);
    }

}

下面是试图连接到websocket的test.html页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
      <body>
        <p>Going to connect to the WebSocket at /endpoint. Check Console</p>
        <button onclick="ss()">Send</button>
      </body>
      <script type="text/javascript">
        var webSocket = new WebSocket("wss://"+document.location.hostname+":8443"+"/endpoint");
        webSocket.onopen = function(message) {
                processOpen(message);
            };
            webSocket.onmessage = function(message) {
                processMessage(message);
            };
            webSocket.onclose = function(message) {
                processClose(message);
            };
            webSocket.onerror = function(message) {
                processError(message);
            };

            function processOpen(message) {
                console.log("JS: Server Connected... "+message);
            }
            function processMessage(message) {
                console.log("Getting a mess: "+message);
            }
            function processClose(message) {
                console.log("JS: Client disconnected... "+message);
            }
            function processError(message) { //
                console.log("Error occured: "+message);
            }
            function ss() {
                webSocket.send("test");
            }
      </script>
</html>

我将websocket路径初始化为/endpoint。这可以从我的服务器日志中看出:

[org.springframework.web.socket.server.support.WebSocketHandlerMapping] (ServerService Thread Pool -- 75) Mapped URL path [/endpoint] onto handler of type [class org.springframework.web.socket.server.support.WebSocketHttpRequestHandler]

当我打开test.html时,连接打开并立即断开。立即依次调用processOpen(message)processClose(message)函数。那么,我做错了什么?我该如何补救?

test.html中的java脚本代码看起来很好。Spring Web套接字配置可能有一些问题,正在关闭连接。下面是带弹簧启动的web套接字的工作代码。请与您的配置进行比较。

pom.xml中的Web套接字依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

WebSocketHandler类

@Component
public class EchoHandler extends TextWebSocketHandler {
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    TextMessage echoMessage = new TextMessage("Echo :" + message.getPayload());
    System.out.println("Sending "+echoMessage.getPayload());
    session.sendMessage(echoMessage);
  }
}
WebSocket控制器类

@EnableWebSocket
@Controller
public class WSController implements WebSocketConfigurer {
@Autowired
private EchoHandler echoHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(echoHandler, "/echo").setAllowedOrigins("*"); 
   }
}

Spring Boot应用类

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

相关内容

  • 没有找到相关文章

最新更新