Skip to content

Provide simple websocket example #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mraible opened this issue Sep 24, 2018 · 8 comments
Closed

Provide simple websocket example #21

mraible opened this issue Sep 24, 2018 · 8 comments

Comments

@mraible
Copy link

mraible commented Sep 24, 2018

I have a simple websocket example that I'm trying to implement with rsocket-js (since I'm connecting to a Spring WebFlux-powered websocket endpoint).

This works using plain ol' websockets:

const socket = new WebSocket('ws://localhost:8080/ws/profiles');
socket.addEventListener('message', (event: any) => {
    window.alert('message from server: ' + event.data);
});

From the current docs, I figured this is equivalent to the following.

// Create an instance of a client
const client = new RSocketClient({
  // send/receive 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: new RSocketWebSocketClient({url: 'ws://localhost:8080/ws/profiles'}),
});

client.connect().subscribe({
  onComplete: (socket: any) => {
    socket.requestResponse();
  },
  onError: (error: any) => console.error(error),
  onNext(payload: any) {
    console.log('onNext(%s)', payload.data);
  },
});

However, I don't get any console logs when I trigger a new websocket event.

Related: does rsocket-js support sending an authorization header in the request like socket.io-client does?

@josephsavona
Copy link
Contributor

josephsavona commented Sep 24, 2018

Does your server support the rsocket protocol? Note that rsocket is a higher level protocol that can use websocket as a transport - neither the client or server can start pushing arbitrary data to the other (as in your WS example) unless it initiates one of the defined actions (request-response, request-stream, etc). In this case the client would typically make a requestResponse with a payload indicating the data it is requesting, and the server would reply with one response (to send multiple payloads use request stream). The corresponding response payload would be accessible via the onComplete handler to requestResponse (missing in your second example).

@mraible
Copy link
Author

mraible commented Sep 24, 2018

@josephsavona It must not. There is an open ticket for WebFlux to support it, so I guess I'll have to wait until that's finished.

@mraible mraible closed this as completed Sep 24, 2018
@yschimke
Copy link
Member

yschimke commented Oct 2, 2018

I think this has been a point of confusion twice now. We should probably make this clearer in the docs if it comes up again.

@walter211
Copy link

I'm the 3rd

@eriktim
Copy link

eriktim commented Jun 27, 2019

I also ran into difficulties getting rsocket to work over WebSockets using a Spring back-end. I ran into this issue so in case anyone needs it here is what I did.

In Java:

// spring.rsocket.server.mapping-path=/rsocket

@Controller
class ReactiveController {
  @MessageMapping('my-message')
  Flux<String> myMessage() {
    return Flux.just("hello world");
  }
}

In JavaScript:

const client = new RSocketClient({
  serializers: {
    data: JsonSerializer,
    metadata: IdentitySerializer
  },
  setup: {
    dataMimeType: 'application/json',
    keepAlive: 100000,
    lifetime: 100000,
    metadataMimeType: 'message/x.rsocket.routing.v0',
  },
  transport: new RSocketWebSocketClient({
    url: 'ws://localhost:8080/rsocket'
  })
});
const socket = await client.connect();
socket.requestStream({
  data: {...},
  metadata: 'my-message'
}).subscribe(...)'

Key part is the metadataMimeType (see https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md) and the metadata value that ensures messages are matched to the right endpoint using Spring's @MessageMapping annotation.

@mmihael
Copy link

mmihael commented Sep 9, 2019

@eriktim for me this is not working.
With the same setup as yours, I had to do this additionally:

metadata: String.fromCharCode(10) + 'my-message'

First 8 bits represent the size of content by doc link you provided (10 being the length of route name). That is not handled by IdentitySerializer.

@mmihael
Copy link

mmihael commented Sep 9, 2019

Also, if you want to send metadata as json object then:

RSocketStrategies rSocketStrategies = applicationContext.getBean(RSocketStrategies.class);

DefaultMetadataExtractor defaultMetadataExtractor = (DefaultMetadataExtractor) rSocketStrategies.metadataExtractor();
defaultMetadataExtractor
	.metadataToExtract(
		MimeTypeUtils.APPLICATION_JSON,
		new ParameterizedTypeReference<Map<String, Object>>() {},
		(metadata, headers) -> metadata.entrySet().forEach(entry -> headers.put(entry.getKey(), entry.getValue()))
	);

Now you only need to have route prop in your metadata object.
In RSocketClient configs, make sure to change metadataMimeType to application/json and change serializer for metadata to JsonSerializer.

@jeisea
Copy link

jeisea commented Sep 26, 2019

@mmihael Were you able to get this working in ie11? On ie11, client.connect() never completes for me. This is using the same setup as @eriktim with your metadata fix.

Any help would be greatly appreciated. Thanks!

EDIT: This might be due to some change in rsocketjs recently?

I have one app using an older version where I am setting metadata like Erik and it completes the connection fine in ie11.

I completion issue occurs in my app using the current version of rsocket js.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants