The server side is encountering difficulty in reading the payload of the requestResponse call

Look at this TS client code snippet below :

this.socketClient.connect().subscribe({
      onComplete: socket => {
        const endpoint = ‚endpoint’;
        socket.requestResponse({
          data: id, //id is a non-empty string
          metadata: String.fromCharCode(endpoint.length) + endpoint
        }).subscribe({
            onComplete: () => console.log(’Task completed’),
            onError: error => {
              console.log('Connection closed due to:: ' + error);
            },
          });
      },
      onError: error => console.error(error),
      onSubscribe: cancel => {}
    });

I need assistance with the proper signature of my server's endpoint. I tried the suggested solution but faced issues. When I debug getEndpoint, the call is processed but id isn't resolved:

@MessageMapping("endpoint")
public Mono<String> getEndpoint(@Payload String id) {
  log.info("requested id:"+id);
  //Server side logic to fetch the relevant 'endpoint' from the database
  return Mono.just(DefaultPayload.create(endpoint));
}

Your support is highly appreciated.

Answer №1

Your customer must provide the routing information that spring-boot relies on to make decisions. Please refer to this article for more details.

Pay close attention to the MIME type when setting up the client, and ensure that the route matches the @MessageMapping in your code.

  // Setting up a client instance
  client = new RSocketClient({
    serializers: {
      data: JsonSerializer,
      metadata: IdentitySerializer
    },
    setup: {
      keepAlive: 60000, // ms between sending keepalive to server
      lifetime: 180000, // ms timeout if no keepalive response
      dataMimeType: 'application/json', // format of `data`
      metadataMimeType: 'message/x.rsocket.routing.v0' // format of `metadata`
    },
    transport: new RSocketWebSocketClient({
      url: 'ws://localhost:8080/tweetsocket'
    }),
  });

  // Establishing the connection
  client.connect().subscribe({
    onComplete: socket => {
      socket.requestStream({
        data: {
          'author': document.getElementById("author-filter").value
        },
        metadata: String.fromCharCode('tweets.by.author'.length) + 'tweets.by.author',
      }).subscribe({
        onComplete: () => console.log('complete'),
        onError: error => {
          console.log(error);
          addErrorMessage("Connection has been closed due to ", error);
        },
        onNext: payload => {
          console.log(payload.data);
          addMessage(payload.data);
        },
        onSubscribe: subscription => {
          subscription.request(2147483647);
        },
      });
    },
    onError: error => {
      console.log(error);
      addErrorMessage("Connection has been refused due to ", error);
    },
    onSubscribe: cancel => {
      /* call cancel() to abort */
    }
  });

Answer №2

Utilizing rsocket within the Spring framework is akin to utilizing API like a Web Socket (). It provides a service, similar to an API, over TCP for client applications to use. In essence, an endpoint in this context refers to a specific URI that is accessed to obtain a data resource, which may look something like ws://localhost:8080/WebsocketTest/testserver or yourtag://url:portnumber/resource, and could even be simply localhost during local testing.

Calling the endpoint ideally involves providing the clientId depending on the design of your rsocket setup. Additionally, it's important to consider what specific service you are aiming to offer through rsocket.

If you're looking for expertise on the subject, check out the following link: https://gitter.im/rsocket/rsocket-java

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

Converting Scss to css during the compilation process in Angular

Seeking assistance with .css and .scss file conversion. I am in need of help with generating or updating a .css file from an existing .scss file during compilation. To explain further: when writing code, everything is going smoothly until I decide to save ...

In TypeScript, is it possible to determine an object's type and then enhance it using a type specified through generics?

I am currently working on a TypeScript function that takes an object as a parameter and deduces its type, then merges that inferred type with another type provided via generics. The outcome should be an object that includes properties from both the inferre ...

What causes Node.js to crash with the Headers already sent Error while managing errors in Express?

My current project involves using Express to set up an API endpoint for user registration. However, I've encountered a problem where sending a request that triggers an error to this API endpoint causes my node.js server to crash. The specific message ...

Converting a Typescript generic type `{[key: string]: T}` into an object literal

I am seeking to create a function that ensures an object adheres to the type {[key: string]: T} and outputs an object literal based on the input argument. For instance, let's say I have the following type A: interface A{ a: string, b: number } I ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Showing object data in TypeScript HTML when the object property starts with a numeral

Below is the function found in the TypeScript file that retrieves data from an API: .ts file getMachineConfigsByid(id) { this.machinesService.getMachineConfigById(id).subscribe((res) => { if (res.status === 'success') { ...

Comparing Input and Output Event Binding

Can you provide reasons why using @Output for events is more advantageous than passing an @Input function in Angular 2+? Utilizing @Input: Parent Template: <my-component [customEventFunction]=myFunction></my-component> Inside parent-compone ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Enhancing ES6 capabilities with Angular polyfills

While exploring the Angular documentation and various online resources about Angular, I came across a question. If all code is written in Typescript, why would we need ES6 polyfills? My understanding is that webpack eventually transpiles the code to ES5, s ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

What steps can I take to allow a third-party JavaScript to access my TypeScript object?

I am working on an Angular application and I have a requirement to develop an API for a third-party JavaScript that will be injected dynamically. public class MyApi{ public callSomeFunction():void{...} public getSomeValue():any {...} } var publicA ...

The incorrect initial state is causing issues in the Zustand state management on the Next.js server side

While utilizing zustand as a global state manager, I encountered an issue where the persisted states were not being logged correctly in the server side of nextjs pages. The log would only show the default values (which are null) and not the updated state v ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

lines stay unbroken in angular

I am encountering an issue when I execute the following code: DetailDisplayer(row) : String { let resultAsString = ""; console.log(row.metadata.questions.length); (row.metadata.questions.length != 0 )?resultAsString += "Questions ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...