幅川

tio-websocket-client 用法

2019-5-23 12:34:34 0 待实现

tio-websocket-client的API风格接近浏览器端的WebSocket API。

1、引用dependence,如maven:

<dependency>
  <groupId>org.t-io</groupId>
  <artifactId>tio-websocket-client</artifactId>
  <version>3.3.1.v20190520-RELEASE</version>
</dependency>

2、创建WebSocket Client:

调用WsClient.create方法创建WsClient:

WsClient create(String uri)
WsClient create(String uri, Map<String, String> additionalHttpHeaders)
WsClient create(String uri, WsClientConfig config)
WsClient create(String uri, Map<String, String> additionalHttpHeaders, WsClientConfig config)

additionalHttpHeaders将添加到HTTP握手包的Header中,主要用于添加token等鉴权行为

例如:

WsClient client = WsClient.create("wss://echo.websocket.org/?encoding=text");
WsClient client = WsClient.create("wss://echo.websocket.org/?encoding=text", Collections.singletonMap("Authorization", "Bearer <token>"));
WsClient client = WsClient.create("wss://echo.websocket.org/?encoding=text", 
                    new WsClientConfig(
                      e -> {
                        System.out.println("emit open");
                      },
                      e -> {
                        WsPacket data = e.data;
                        System.out.println("recv "+data.getWsText());
                      },
                      e -> {
                        System.out.println(
                            String.format("emit close: %d, %s, %s", e.code, e.reason, e.wasClean));
                      },
                      e -> {
                        System.out.println(String.format("emit error: %s", e.msg));
                      },
                      Throwable::printStackTrace));

3、调用client.connect()连接到服务器

WebSocket ws = echo.connect();

4、像前端一样使用WebSocket

ws.addOnMessage(e -> {
    // ...
});

ws.send("message");

使用https://www.websocket.org/echo.html的echo服务的完整示例:

public static void main(String[] args) throws Exception {
    Map<Integer, Boolean> sent = new ConcurrentHashMap<>();
    int total = 1000;

    Subject<Object> complete = PublishSubject.create().toSerialized();
    complete
        .buffer(total)
        .subscribe(
            x -> {
              Boolean all = sent.values().stream().reduce(true, (p, c) -> p && c);
              if (all) {
                System.out.println("All sent success! ");
              }
            });

    WsClient echo =
        WsClient.create(
            "wss://echo.websocket.org/?encoding=text",
            new WsClientConfig(
                e -> System.out.println("opened"),
                e -> {
                  WsPacket data = e.data;
                  int i = Integer.parseInt(data.getWsBodyText());
                  sent.put(i, true);
                  System.out.println("recv: " + i);
                  complete.onNext(i);
                },
                e -> System.out.printf("on close: %d, %s, %s\n", e.code, e.reason, e.wasClean),
                e -> System.out.println(String.format("on error: %s", e.msg)),
                Throwable::printStackTrace));

    WebSocket ws = echo.connect();

    for (int i = 0; i < total; i++) {
      ws.send("" + i);
      sent.put(i, false);
      System.out.println("sent: " + i);
    }
  }
TCP连接数:, IP数:
    发 送