Javalin Websocket客户端静默无法连接

时间:2020-04-13 18:31:45

标签: java websocket javalin

我正在尝试创建一个与Websocket服务器对话的Websocket客户端。我的服务器代码似乎运行正常,因为我可以使用基于Web的客户端连接到它。但是我的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构建器代码,但是正如我所说,当我运行main并与运行在其中的服务器处于循环中时,我可以使用https://websocketking.com/ws://localhost:7000/websocket上连接到它后台线程。

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 ()

布拉德

PS:

我将连接更改为阻塞连接,并出于原因在客户端的onClose()方法中添加了打印出来的内容,

org.java_websocket.drafts.Draft_10@2025740c refuses handshake

老实说,我不知道草稿库在做什么,所以接下来请继续阅读。

1 个答案:

答案 0 :(得分:0)

因此不推荐使用DRAFT_10参考。将其更新为最新版本

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