I’m trying to receive a buffer through a TCP socket using the TServerSocket component (I’m maintaining a legacy application, so migrating to Indy or anything else is out of question for now).
I have implemented a method of the OnClientRead event that reads this buffer in a non-blocking socket (again, I cannot make drastic changes to this legacy application).
The function looks like this:
procedure TFrmMain.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Size: Integer;
Bytes: TBytes;
begin
Size := Socket.ReceiveLength;
SetLength(Bytes, Size);
Socket.ReceiveBuf(Bytes, Size);
end;
However, this gives me the following exception:
Asynchronous socket error 10053
If I change it to this:
procedure TFrmMain.ServerSocket1ClientRead(Sender: TObject;
Socket: TCustomWinSocket);
var
Size: Integer;
Bytes: array[0..1024*256] of Byte;
begin
Size := Socket.ReceiveLength;
Socket.ReceiveBuf(Bytes, Size);
end;
It works. However, the dynamic approach is more adequate to my problem domain.
What could be causing this? My objective is to read a binary buffer through a TCP socket with this component.
Thanks in advance.
The first parameter of
ReceiveBufis an untyped var parameter. It needs direct access to the place it’s going to start writing.When you pass it a dynamic array, it will overwrite the dynamic-array variable itself instead of the contents of the array. Pass a reference to the first element of the array instead of a reference to the variable:
That syntax will work with non-dynamic arrays, too. In that case, a reference to the first element is the same as a reference to the variable itself.