0

我正在尝试创建一个与 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 并坐在循环中,服务器在后台线程中运行时,我可以ws://localhost:7000/websocket使用https://websocketking.com/连接到它。

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

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

4

1 回答 1

0

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

WebSocketClient mWs = new WebSocketClient(
        new URI( "ws://127.0.0.1:7000/websocket" ),
        new Draft_6455()
    )
于 2020-04-14T10:09:53.333 回答