Jump to content
kindox

Send binary data from WebSocket server app

Recommended Posts

I want to implement a Delphi WebSocket server to send binary data (Stream and byte array) to javascript client. This could be done after receive a client message OR EVEN as unidirectional message so no client message need to be received. Below the pseudocode.

var
  WSServer: TWSocketServer;


Case A: I want to send back the binary data after receive a message

WSServer.OnClientConnect := procedure (Sender: TObject; Client: TWSocketClient; Error: Word)
begin
  TWebSockSrvClient(Client).OnWebSocketMessage := WebSocketMessage;
end;

procedure WebSocketMessage(Sender: TObject; Msg: string);
var
  MemStream: TMemoryStream;
  SocketConn: IWebSocketConnection;
begin
  //create and populate MemStream
  if (Msg = 'A') then
  begin
    SocketConn := TWebSocketSocket(Sender).getConnection;

    //I need to send back the MemStream but I found only these method:  
    //SocketConn.sendString
    //SocketConn.sendFrame
    //SocketConn.sendMessage
  end;
end;

 

Case B: send binary data to some client from button click

procedure TForm1.btnSendBufferClick(Sender: TObject);
var
  ArrB: TBytes;
begin
  ArrB := [1, 2, 3];
  //I tried WSServer.Client[0].SendTB(ArrB) but is doesn't work
end;

 

I check OverbyteIcsWebSocketSrv.dpr demo but only strings are send.

 

Any advice?

Share this post


Link to post

The Web Socket Server was written by Stan Korotky some time ago, and adds a protocol on top of the normal TWSocketServer component, so you can not use client methods.

 

But the component only sends AnsiStrings, so just copy your binary data into an AnsiString and send that. 

 

Angus

 

Share this post


Link to post

Thanks @Angus Robertson

 

I need to send a very big buffer (1 GB) of float array so I didn't want to waste time and memory duplicating the data. In addition, if it's only possible to send strings I need to waste time and memory in Javascript converting the data when it arrives because buffer is not created as ArrayBuffer or Blob but string.

 

I thought this library was able to send binary frames (opcode = 0x02) but according to your answer it doesn't. Anyway I appreciate your reply.

 

Do you know any free websocket library to do this?

Edited by kindox

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×