0

I am working on a project where I am getting data in binary format but I am not able to understand how to decode the binary message into JSON Format.

I have attached the below screenshot where in that they have mentioned how to handle binary message but I am not able to understand this can anyone help me on this.

enter image description here

Header Response:

enter image description here

Binary Message ScreenShot enter image description here

Below is the code snippet of websocket using angular rxjs.

 import { Injectable } from '@angular/core';
 import { webSocket } from 'rxjs/webSocket';
 import { Observable, timer, Subject, EMPTY } from 'rxjs';
 import { retryWhen, tap, delayWhen, switchAll, catchError } from 'rxjs/operators';
 import { SessionStorageService } from '../session-storage.service';
 import { SessionStorageKeys } from 'src/app/constants/storageKeys';
 import { JarvisAlgoPartnerUser } from 'src/app/modal/JarvisAlgoUser';
 export const RECONNECT_INTERVAL = 5;

 @Injectable({
   providedIn: 'root'
 })
 export class DataService {

   private socket$;
   private messagesSubject$ = new Subject();
   public messages$ = this.messagesSubject$.pipe(switchAll(), catchError(e => { throw e }));
   WS_ENDPOINT = "wss://ant.aliceblueonline.com/hydrasocket/v2/websocket?access_token=";

   constructor(private storage: SessionStorageService) {
   }

   /**
    * Creates a new WebSocket subject and send it to the messages subject
    * @param cfg if true the observable will be retried.
    */
   public connect(cfg: { reconnect: boolean } = { reconnect: false }): void {


     if (!this.socket$ || this.socket$.closed) {
       this.socket$ = this.getNewWebSocket();
       const messages = this.socket$.pipe(cfg.reconnect ? this.reconnect : o => o,
         tap({
           error: error => {
             debugger;
             console.log(error)
           },
         }), catchError(_ => EMPTY))
       //toDO only next an observable if a new subscription was made double-check this
       this.messagesSubject$.next(messages);
     }
   }

   /**
    * Retry a given observable by a time span
    * @param observable the observable to be retried
    */
   private reconnect(observable: Observable<any>): Observable<any> {
     return observable.pipe(retryWhen(errors => errors.pipe(tap(val => 
       console.log('[Data Service] Try to reconnect', val)),
       delayWhen(_ => timer(RECONNECT_INTERVAL)))));
   }

   subscribe() {
     this.socket$.subscribe();
   }


   close() {
     this.socket$.complete();
     this.socket$ = undefined;
   }

   sendMessage(msg: any) {
     this.socket$.next(msg);

   }

   /**
    * Return a custom WebSocket subject which reconnects after failure
    */
   private getNewWebSocket() {
     var partnerToken = JSON.parse(this.storage.GetSessionStorage(SessionStorageKeys.Token)) 
      as JarvisAlgoPartnerUser[];

     var partner = partnerToken.filter(item => item.partnerName === 'ANT' 
       && item.generateToken !== '')[0];
     var websocketURL = "";
     if (partner != null) {
       websocketURL = this.WS_ENDPOINT + partner.generateToken;
     }
     return webSocket({
       url: websocketURL,
       openObserver: {
         next: (res) => {
           console.log('[DataService]: connection ok' + res);
         }
       },
       closeObserver: {
         next: () => {
           console.log('[DataService]: connection closed');
           this.socket$ = undefined;
           this.connect({ reconnect: true });
         }
       },

     });
   }
 }

Note: the token has the validity of one day.... let me know if you want to try from your end so that I can provide you the latest token.

vijay sahu
  • 765
  • 1
  • 7
  • 29
  • I feel that you can check the WebSocket library for this if they have any such mechanism to change this message into some readable format – Deepak Jha Dec 22 '21 at 18:30
  • You can check this answers https://stackoverflow.com/questions/21354235/converting-binary-to-text-using-javascript/21354328 – Mohammad Babaei Dec 22 '21 at 20:58

2 Answers2

0

Try some library for decode. For example decode-encode lib

This is not a library for angular, but you can definitely find something similar, and it shouldn't be a problem to use it anyway. At least to verify that this solves your problem.

Daniel Vágner
  • 538
  • 3
  • 19
0

Add deserializer: msg => msg

return webSocket({
      url: environment.baseUrl,
      binaryType: "arraybuffer",
      deserializer: msg => msg,
      openObserver: {
        next: () => {
          console.log('Connected');
        }
      },
      closeObserver: {
        next: () => {
          console.log('Connection closed');
          this.socket$ = undefined;
          this.connect({ reconnect: true });
        }
      },
    });
Joosep Parts
  • 5,372
  • 2
  • 8
  • 33