简体   繁体   English

JavaScript客户端无法连接到Spring 4 WebSocket

[英]JavaScript client cannot connect to Spring 4 WebSocket

I have implemented websocket in spring but the JavaScript client cannot connect to the websocket. 我在春季实现了websocket,但是JavaScript客户端无法连接到websocket。

Here is the WebSocketConfig class: 这是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);
    }


}

Here is the test.html page that tries to connect to the websocket: 这是尝试连接到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>

I initialized the websocket path to be at /endpoint . 我将websocket路径初始化为/endpoint This is evident by my server logs which say that this has occurred: 我的服务器日志表明这已经发生:

[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]

When I open up test.html , the connection opens and immediately disconnects. 当我打开test.html ,连接打开并立即断开连接。 The processOpen(message) and processClose(message) function are immediately called, one after the other. 立即调用processOpen(message)processClose(message)函数,一个接一个。 So what am I doing wrong, and how can I fix this? 那么我在做什么错了,我该如何解决呢?

Your java-script code in test.html looks fine. 您在test.html中的Java脚本代码看起来不错。 There could be some issue with Spring Web socket configuration which is closing the connection. Spring Web套接字配置可能会出现一些问题,该配置正在关闭连接。 Following is the working code for web socket with spring boot. 以下是带弹簧启动的Web套接字的工作代码。 Please compare with your configuration. 请与您的配置进行比较。

Web socket dependency in pom.xml pom.xml中的Web套接字依赖项

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

WebSocketHandler class 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 Controller class 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 application class Spring Boot应用程序类

@SpringBootApplication
public class WSApplication {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM