TCustomWinSocket的ReceiveBuf不适用于缓冲区的动态数组 [英] ReceiveBuf from TCustomWinSocket won't work with dynamic arrays for the buffer

查看:209
本文介绍了TCustomWinSocket的ReceiveBuf不适用于缓冲区的动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用TServerSocket组件通过TCP套接字接收缓冲区(我正在维护旧版应用程序,因此现在迁移到Indy或其他任何设备都没有问题)。

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).

我实现了OnClientRead事件的方法,该方法读取非阻塞套接字中的此缓冲区(再次,我无法对该旧版应用程序进行大刀阔斧的更改)。

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).

函数如下所示:

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

如果将其更改为

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.

这可能是什么原因造成的?我的目标是通过带有此组件的TCP套接字读取二进制缓冲区。

What could be causing this? My objective is to read a binary buffer through a TCP socket with this component.

预先感谢。

推荐答案

ReceiveBuf 的第一个参数是无类型的var参数。它需要直接访问将要开始写入的位置。

The first parameter of ReceiveBuf is 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:

Socket.ReceiveBuf(Bytes[0], Size);

该语法也适用于非动态数组。在这种情况下,对第一个元素的引用与对变量本身的引用相同。

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.

这篇关于TCustomWinSocket的ReceiveBuf不适用于缓冲区的动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆