如何用JavaScript编写RSocket客户端

时间:2019-09-18 12:54:22

标签: javascript websocket reactive-streams rsocket

我尝试用Java实现RSocket服务器,并用JavaScript实现客户端,但是我无法在后端调用任何方法。

Java服务器

public final class RawServer {
    public static void main(String[] args) {
        RSocketFactory.receive()
                .acceptor((setup, sendingSocket) -> Mono.just(new DefaultSimpleService()))
                .transport(WebsocketServerTransport.create("localhost", 8801))
                .start()
                .block()
                .onClose()
                .block();
    }

    private static final class DefaultSimpleService extends AbstractRSocket {
        private ObjectMapper jsonMapper = new ObjectMapper();

        @Override
        public Flux<Payload> requestStream(Payload payload) {
            return Mono.just(payload.getDataUtf8())
                    .map(json -> {
                        try {
                            return jsonMapper.readValue(json, Message.class);
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    })
                    .doOnNext(msg -> System.out.println("got message " + msg.message))
                    .flatMapMany(msg -> Flux.range(0, 5)
                            .map(count -> msg.message + " #" + count))
                    .map(message -> DefaultPayload.create(message));
        }
    }
}

public class Message {

    public final String message;

    @JsonCreator
    public Message(@JsonProperty("message") String message) {
        this.message = message;
    }
}

JavaScript客户端

    import { RSocketClient, JsonSerializers } from "rsocket-core";
    import RSocketWebSocketClient from "rsocket-websocket-client";

    const transport = new RSocketWebSocketClient({
        url: "ws://localhost:8801"
      });

      const client = new RSocketClient({
        // send/receive JSON objects instead of strings/buffers
        serializers: JsonSerializers,
        setup: {
          // ms btw sending keepalive to server
          keepAlive: 60000,
          // ms timeout if no keepalive response
          lifetime: 180000,
          // format of `data`
          dataMimeType: "application/json",
          // format of `metadata`
          metadataMimeType: "application/json"
        },
        transport
      });
      client.connect().subscribe({
        onComplete: socket => {
          socket.requestStream({
            data: { message: "hello from javascript!" },
            metadata: null
          });
        },
        onError: error => {
          console.log("got error");
          console.error(error);
        },
        onSubscribe: cancel => {
          /* call cancel() to abort */
          console.log("subscribe!");
          console.log(cancel);
          // cancel.cancel();
        }
      });

似乎WebSocket连接已建立,但没有消息推送到服务器。我该怎么办?

我还用Java实现了客户端,而且一切正常。我发现的JavaScript示例是https://github.com/rsocket/rsocket-js/blob/master/docs/01-client-configuration.md,但我无法使其正常工作。

1 个答案:

答案 0 :(得分:0)

有关RSocket的更多示例,您可以访问我的个人博客http://kojotdev.com/2019/09/rsocket-examples-java-javascript-spring-webflux/

好,我知道了。首先,我们需要修复服务器以返回正确的JSON对象。

@Override
public Flux<Payload> requestStream(Payload payload) {
    log.info("got requestStream in Server");
    log.info(payload.getDataUtf8());
    return Mono.just(payload.getDataUtf8())
            .map(payloadString -> MessageMapper.jsonToMessage(payloadString))
            .flatMapMany(msg -> Flux.range(0, 5)
                    .map(count -> msg.message + " | requestStream from Server #" + count)
                    .map(responseText -> new Message(responseText))
                    .map(responseMessage -> MessageMapper.messageToJson(responseMessage)))
            .map(message -> DefaultPayload.create(message));
}

然后,在我们的JavaScript客户端中,我们需要将socket.requestStream方法更改为此:

socket
  .requestStream({
    data: { message: "request - stream from javascript!" },
    metadata: ""
  })
  .subscribe({
    onComplete: () => console.log("requestStream done"),
    onError: error => {
      console.log("got error with requestStream");
      console.error(error);
    },
    onNext: value => {
      // console.log("got next value in requestStream..");
      console.log(value.data);
    },
    // Nothing happens until `request(n)` is called
    onSubscribe: sub => {
      console.log("subscribe request Stream!");
      sub.request(7);
    }
  });

所有其他内容均与上一个示例相同。 有用的链接: