Javalin Websocket 客户端无提示连接失败

标签 java websocket javalin

我正在尝试创建一个与 Websocket 服务器通信的 Websocket 客户端。我的服务器代码似乎运行正常,因为我可以使用基于网络的客户端连接到它。但我的 Java 实现只是默默地无法连接,然后在 send() 上抛出异常。

这是我用于尝试此操作的临时装备:

更新: 我发现问题是示例代码使用了已弃用的 DRAFT 版本。我更新了,现在可以让两个线程相互交谈。我已更新代码以显示工作版本。

我现在的一个问题是如何关闭服务器?

package com.github.museadmin.api;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;

public class WsThreadRig {

  private static final String threadName = "ism_thread";

  public static void main(String[] args) throws InterruptedException, URISyntaxException {

    ISMWebSocket server = new ISMWebSocket.Builder()
        .port(7000)
        .uri("/websocket")
        .identity("server")
        .host("localhost")
        .build();

    Thread thread = new Thread (server, threadName);
    thread.start ();
    Thread.sleep(1000L);

    WebSocketClient mWs = new WebSocketClient(
        new URI( "ws://127.0.0.1:7000/websocket" ),
        new Draft_6455()
    )
    {
      @Override
      public void onMessage( String message ) {
        System.out.println(
            String.format("Message received from server (%s)",
            message)
        );
      }

      @Override
      public void onOpen( ServerHandshake handshake ) {
        System.out.println( "Client opened connection" );
      }

      @Override
      public void onClose( int code, String reason, boolean remote ) {
        System.out.println(
            String.format("Client closed connection because (%s)", reason)
        );
      }

      @Override
      public void onError( Exception ex ) {
        ex.printStackTrace();
      }

    };

    //open websocket
    mWs.connectBlocking();
    Thread.sleep(1000L);
    String message = "Test message from client";
    //send message
    mWs.send(message);
    mWs.close();
  }
}

我将在下面包含 Websocket 构建器代码,但正如我所说,我可以使用 https://websocketking.com/ws://localhost:7000/websocket 上正常连接到它。当我运行 main 并坐在循环中,服务器在后台线程中运行。

package com.github.museadmin.api;

import io.javalin.Javalin;

import java.util.Optional;

public class ISMWebSocket implements Runnable {

  private Integer port;
  private String uri;
  private String identity;
  private String host;

  private ISMWebSocket(Builder builder) {
    this.port = builder.port;
    this.uri = builder.uri;
    this.identity = builder.identity;
  }

  @Override
  public void run() {
    Javalin app = Javalin.create().start(this.host, this.port);
    app.ws(this.uri, ws -> {
      ws.onConnect(ctx -> {
          System.out.println("Client connected to server");
          ctx.send("Test message from server");
        }
      );
      ws.onClose(ctx -> {
          System.out.println("Client disconnected from server");
        }
      );
      ws.onMessage(ctx -> System.out.println(
          String.format("Message received from client (%s)", ctx.message())
        )
      );
      ws.onError(ctx -> {
        System.out.println(
            String.format("ERROR: (%s)", ctx.error().getMessage())
        );
      });
    });
  }

  public Optional<Integer> getPort() {
    return Optional.ofNullable(port);
  }

  public Optional<String> getUri() {
    return Optional.ofNullable(uri);
  }

  public Optional<String> getIdentity() {
    return Optional.ofNullable(identity);
  }

  public Optional<String> getHost() {
    return Optional.ofNullable(host);
  }


  public static class Builder {
    private Integer port;
    private String uri;
    private String identity;
    private String host;

    public Builder port(Integer port) {
      this.port = port;
      return this;
    }

    public Builder uri(String uri) {
      this.uri = uri;
      return this;
    }

    public Builder identity(String identity) {
      this.identity = identity;
      return this;
    }

    public Builder host(String host) {
      this.host = host;
      return this;
    }

    public Builder fromPrototype(ISMWebSocket prototype) {
      port = prototype.port;
      uri = prototype.uri;
      identity = prototype.identity;
      host = prototype.host;
      return this;
    }

    public ISMWebSocket build() {
      return new ISMWebSocket(this);
    }
  }
}

这是输出:

Client opened connection
Client connected to server
Message received from server (Test message from server)
Message received from client (Test message from client)
Client disconnected from server
Client closed connection because ()

布拉德

附注:

我将连接更改为阻塞连接,并在客户端的 onClose() 方法中添加了打印原因,现在报告:

org.java_websocket.drafts.Draft_10@2025740c 拒绝握手

说实话,我不知道草稿库在做什么,所以接下来会仔细阅读。

最佳答案

因此 DRAFT_10 引用已被弃用。已更新至最新版本

WebSocketClient mWs = new WebSocketClient(
        new URI( "ws://127.0.0.1:7000/websocket" ),
        new Draft_6455()
    )

关于Javalin Websocket 客户端无提示连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194307/

相关文章:

java - Magnolia CMS - 如何使用 LinkFieldDefinition 重置所选值?

javascript - Pusher 订阅私有(private) channel - 无法获取身份验证信息

ssl - NodeMCU Lua Websockets 安全不适用于 2.0 基线

java - 隔离注解的实例化

regex - 暴露的JetBrains(DSL Api):使用.regexp()时出现问题的情况

java - Intellij Linux JVM Debugger在哪个Pi目录中运行

java - Sceneform ARCore 加载并构建随机 3D 资源

java - Spring data findone 未获取最新数据

java - 在 Gradle 构建 JAR 中多次包含具有不同名称的文件

iframe - 试图弄清楚为什么谷歌分析报告的用户比我们自己的堆栈多