java - WebSocket DeploymentException 连接失败

标签 java ssl websocket spring-websocket

我正在开发 Websocket Java 客户端,但我总是无法连接到服务器。 感谢您帮助我。

错误信息

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: javax.websocket.DeploymentException: Connection to 'wss://localhost:8443/index' failed.
    at com.lge.racss.test.WebsocketClientEndpoint.<init>(WebsocketClientEndpoint.java:88)
    at com.lge.racss.test.Application.main(Application.java:16)
    ... 6 more
Caused by: javax.websocket.DeploymentException: Connection to 'wss://localhost:8443/index' failed.
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientSocket._connect(GrizzlyClientSocket.java:382)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientSocket.access$000(GrizzlyClientSocket.java:103)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientSocket$1.call(GrizzlyClientSocket.java:228)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientSocket$1.call(GrizzlyClientSocket.java:224)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientSocket.connect(GrizzlyClientSocket.java:242)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientContainer.openClientSocket(GrizzlyClientContainer.java:95)
    at org.glassfish.tyrus.client.ClientManager$1$1.run(ClientManager.java:575)
    at org.glassfish.tyrus.client.ClientManager$1.run(ClientManager.java:622)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.glassfish.tyrus.client.ClientManager$SameThreadExecutorService.execute(ClientManager.java:775)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
    at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:447)
    at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:337)
    at com.lge.racss.test.WebsocketClientEndpoint.<init>(WebsocketClientEndpoint.java:84)
    ... 7 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 35.841 s
[INFO] Finished at: 2017-01-25T15:41:21+09:00
[INFO] Final Memory: 19M/172M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project SignalingServerTest: An exception occured while executing the Java class. null: InvocationTargetException: javax.websocket.DeploymentException: Connection to 'wss://localhost:8443/index' failed. -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

WebSocketClientEndPoint 类

package com.lge.racss.test;

import java.net.URI;
import java.net.URISyntaxException;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

import org.glassfish.grizzly.ssl.SSLContextConfigurator;
import org.glassfish.tyrus.client.ClientManager;
import org.glassfish.tyrus.client.ClientProperties;
import org.glassfish.tyrus.client.SslContextConfigurator;
import org.glassfish.tyrus.client.SslEngineConfigurator;


@ClientEndpoint
public class WebsocketClientEndpoint {

    Session userSession = null;
    private MessageHandler messageHandler;

    public WebsocketClientEndpoint(URI endpointURI) {
        try {
            System.getProperties().put(SSLContextConfigurator.KEY_STORE_FILE, "/etc/keystore/keystore.jks");
            System.getProperties().put(SSLContextConfigurator.TRUST_STORE_FILE, "/etc/keystore/server");
            System.getProperties().put(SSLContextConfigurator.KEY_STORE_PASSWORD, "123456");
            System.getProperties().put(SSLContextConfigurator.TRUST_STORE_PASSWORD, "123456");
            ClientManager client = ClientManager.createClient();
            SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(new SslContextConfigurator());
            sslEngineConfigurator.setHostVerificationEnabled(false); //skip host verification
            client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator);
            System.out.println("before connect");
            client.connectToServer(this, endpointURI);
            System.out.println("after connect");

            /*WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
            */
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Callback hook for Connection open events.
     *
     * @param userSession the userSession which is opened.
     */
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    /**
     * Callback hook for Connection close events.
     *
     * @param userSession the userSession which is getting closed.
     * @param reason the reason for connection close
     */
    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    /**
     * Callback hook for Message Events. This method will be invoked when a client send a message.
     *
     * @param message The text message
     */
    @OnMessage
    public void onMessage(String message) {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    /**
     * register message handler
     *
     * @param msgHandler
     */
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    /**
     * Send a message.
     *
     * @param message
     */
    public void sendMessage(String message) {
        this.userSession.getAsyncRemote().sendText(message);
    }

    /**
     * Message handler.
     *
     * @author Jiji_Sasidharan
     */
    public static interface MessageHandler {

        public void handleMessage(String message);
    }
}

应用类

package com.lge.racss.test;

import java.net.URI;
import java.net.URISyntaxException;


public class Application {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        URI uri;
        try {
            uri = new URI("wss://localhost:8443/index");
            System.out.println("webSoekt Address : "+uri.toString());
            final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(uri);
            System.out.println("after clientEndPoint");
            // add listener
            clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
                public void handleMessage(String message) {
                    System.out.println(message);
                }
            });
            System.out.println("add listener");
            // send message to websocket
            clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");
            System.out.println("send");
            // wait 5 seconds for messages from websocket
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.lge.racss.test</groupId>
  <artifactId>SignalingServerTest</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SignalingServerTest Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
    <version>1.1</version>
</dependency>

    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
    </dependency>
     <dependency>
        <groupId>org.glassfish.tyrus</groupId>
        <artifactId>tyrus-container-grizzly-client</artifactId>
        <version>1.8.3</version>
  </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.1</version>
    </dependency>
    <dependency>
    <groupId>org.apache.ibatis</groupId>
    <artifactId>ibatis-core</artifactId>
    <version>3.0</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
    <groupId>com.neovisionaries</groupId>
    <artifactId>nv-websocket-client</artifactId>
    <version>1.31</version>
</dependency>
  </dependencies>
  <build>
    <finalName>SignalingServerTest</finalName>
    <plugins>
             <plugin>
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
                 <version>3.1</version>
                 <configuration>
                     <source>1.7</source>
                     <target>1.7</target>
                 </configuration>
             </plugin>
            <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>java</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <mainClass>com.lge.racss.test.Application</mainClass>
            </configuration>
            </plugin>
    </plugins>
  </build>
</project>

这些都是我客户端使用的代码。从另一个用javascript制作的客户端连接到Server成功。

wssUrl = "wss://localhost:8443/index"
this.client = new WebSocket(wssUrl);

我认为应该修改Java websocket Client的配置或者在配置中插入一些东西。 你对这些人有什么想法吗? 帮帮我。

最佳答案

您的 URL 缺少尾部斜杠。应该是 wss://localhost:8443/index/

关于java - WebSocket DeploymentException 连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41845319/

相关文章:

php - Cloud Foundry 上的 DokuWiki "Your PHP seems to miss SSL support"

ssl - 在wireshark中,为什么显示的IP数据包总长度比在线捕获的帧少1个字节?

javascript - 在 Angular2 应用程序中使用 angular2-websocket 关闭时如何重新连接 websocket 连接?

java - 改进 Java 中将 Json 转换为 XML 或反之亦然的程序

java - 等价于 c# 中的 matcher.start 和 matcher.end

java - 将 JTable 导出到 Excel 文件

Java SHA1withDSA 到 PHP,可转换吗?

.htaccess - 2-redirect HSTS 而不是 1-redirect HSTS 的优势是什么

json - 如何使用 Golang 从 websocket 读取值

javascript - Node.js WebSocket 广播