使用websocket发送原始数据,最好的方法是什么?

时间:2018-06-13 17:56:10

标签: delphi websocket

使用Delphi Berlin 10.2

我们在我们的应用程序中使用WebSocket(使用组件TsgcWebSocketClient)。有两种方法可以通过此组件传输数据,一种方法使用String in参数,另一种方法使用TStream。我们需要发送原始数据。所以我们每次创建一个TStream并发送。 在您看来,这是最好的方法吗? 我们想要发送原​​始数据而无需每次都在TStream中进行转换。

代码如下。

你怎么看?

procedure OnBinary(Connection: TsgcWSConnection; const Data: TMemoryStream);

procedure EnviarComando;    
var
 tmpBytes: TBytes;  
begin
   SetLength(tmpBytes, 5);
   tmpBytes[0] := 1;
   tmpBytes[1] := 2;
   tmpBytes[2] := 3;
   tmpBytes[3] := 13;
   tmpBytes[4] := $F3;
   tmpStream := TMemoryStream.Create;
   tmpStream.WriteBuffer(tmpBytes, 5);
   _webSocket.WriteData(tmpStream);
   tmpStream.Free;
 end;
end;

提前Tks!

1 个答案:

答案 0 :(得分:4)

Delphi有一个TBytesStream类。您无需将TBytes复制到TMemoryStream,而是可以按原样发送TBytes

procedure EnviarComando;    
var
  tmpBytes: TBytes;  
  tmpStream: TBytesStream;
begin
  SetLength(tmpBytes, 5);
  tmpBytes[0] := 1;
  tmpBytes[1] := 2;
  tmpBytes[2] := 3;
  tmpBytes[3] := 13;
  tmpBytes[4] := $F3;
  tmpStream := TBytesStream.Create(tmpBytes);
  try
    _webSocket.WriteData(tmpStream);
  finally
    tmpStream.Free;
  end;
end;

否则,您可以将TBytesWrite()字节直接删除到TMemoryStream

procedure EnviarComando;    
const
  cBytes: array[0..4] of Byte = (1, 2, 3, 13, $F3);
var
  tmpStream: TMemoryStream;
begin
  tmpStream := TMemoryStream.Create;
  try
    tmpStream.WriteBuffer(cBytes, Length(cBytes));
    tmpStream.Position := 0;
    _webSocket.WriteData(tmpStream);
  finally
    tmpStream.Free;
  end;
 end;
end;

或者:

type
  TMemoryStreamAccess = class(TMemoryStream)
  end;

procedure EnviarComando;    
var
  tmpStream: TMemoryStream;
begin
  tmpStream := TMemoryStream.Create;
  try
    TMemoryStreamAccess(tmpStream).Capacity := 5;
    tmpStream.WriteData(UInt8(1));
    tmpStream.WriteData(UInt8(2));
    tmpStream.WriteData(UInt8(3));
    tmpStream.WriteData(UInt8(13));
    tmpStream.WriteData(UInt8($F3));
    tmpStream.Position := 0;
    _webSocket.WriteData(tmpStream);
  finally
    tmpStream.Free;
  end;
end;