Recent

Author Topic: Websocket and arraybuffer  (Read 2260 times)

dennis_uniwin

  • Newbie
  • Posts: 6
Websocket and arraybuffer
« on: June 27, 2023, 11:13:41 am »
Hello,

I started with the websocket demo and I am trying to make a websocket connection to our own software.
So I have made sure that the websocket is created in the following way:
Code: Pascal  [Select][+][-]
  1.      
  2.   URL:='ws://'+aHost+':5001/ws/';
  3.     end;
  4.   try
  5.     WS:=TJSWebsocket.New(url,'csr');
  6.     ws.binaryType:='arraybuffer';
  7.     WS.onopen:=@DoOpen;
  8.     WS.onmessage:=@DoIncomingMessage;
  9.     WS.onclose:=@DoClosed;  

The connection is made and I receive a message from out software. In the DoIncomingMessage event I try to handle the received data.
This should be an ArrayBuffer. And I try to handle this in the following way. Only myarray remains an array with a length of 0. So obviously I am doing something wrong. Does someone know what it is I am doing wrong? And the next question how do I cast the byte array to a string?

Code: Pascal  [Select][+][-]
  1. var
  2.   mystring: string;
  3.   myarray:TJSUint8Array;    
  4. begin
  5.     myarray := TJSUint8Array.new(TJSUint8Array.from(Msg.Data));
  6.     mystring := myarray.toLocaleString;
  7.    Writeln(mystring);
  8.    end;  
  9.  

Thaddy

  • Hero Member
  • *****
  • Posts: 16194
  • Censorship about opinions does not belong here.
Re: Websocket and arraybuffer
« Reply #1 on: June 27, 2023, 12:46:12 pm »
Since UTF8, UTF8 and UTF32 can at some point contain 4 bytes per character, your buffer needs to assume SizeOf(Byte) * 4 in all cases.... Basic...
If I smell bad code it usually is bad code and that includes my own code.

dennis_uniwin

  • Newbie
  • Posts: 6
Re: Websocket and arraybuffer
« Reply #2 on: June 27, 2023, 03:18:51 pm »
I got it! I first had to make it an TJSObject and then a TJSUint8Array and then I can create a readable string finally.
Code: Pascal  [Select][+][-]
  1.      myObject := toObject(Msg.Data);
  2.      myarray  := TJSUint8Array.new(myObject);    
  3.      for i := 0 to myarray.byteLength - 1 do begin
  4.        mystring:= mystring + Char(myarray.values[i]);
  5.      end;
  6.      Writeln('myString ' + mystring);    
  7.  



 

TinyPortal © 2005-2018